zoukankan      html  css  js  c++  java
  • Socket类的用法

    Socket可以理解成一个IP地址加一个端口

    在客户端上我们只需要一个Socket,但是在服务端上,我们需要用一个Socket来监视某端口,然后根据来访的客户端来建立新的Socket负责数据通信。

    代码总结如下:
    服务端:

    //1.服务器端定义用于监听的Socket对象:
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    //设定IP和端口
    IPAddress ip = IPAddress.Parse(IP地址字符串);
    IPEndPoint point = new IPEndPoint(ip, int.Parse(端口字符串));
    //把IP和端口绑定到Socket上
    socket.Bind(point);
    //设置可同时排队的人数
    socket.Listen(count);
    
    //2.开启新线程(Listen方法)进行监听:
    Thread th = new Thread(Listen);
    th.IsBackground = true;
    th.Start();
    
    //3.在新线程(Listen方法中)循环监听:
    while (true)
    {
        //新建一个叫connect的Socket,监听socket的IP地址和端口号
        connect = socket.Accept();
        //开启新线程(RecMsg方法)用于接收消息
        Thread th = new Thread(RecMsg);
        th.IsBackground = true;
        th.Start();
    }
    
    //4.在新线程(RecMsg方法中)循环接收消息:
    while (true)
    {
        byte[] buffer = new byte[length];
        //如果连接没关
        if (connect.Connected)
        {
            //用connect接收消息,返回接收到的长度
            int length = connect.Receive(buffer);
            //处理或显示消息
            ....
        }
    }

    客户端:

    //1.客户端端定义用于发送信息的Socket对象并连接服务器:
    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPAddress ip = IPAddress.Parse(服务器IP地址字符串);
    IPEndPoint point = new IPEndPoint(ip, int.Parse(服务器端口字符串));
    client.Connect(point);
    
    //2.定义好byte数组buffer,给服务器发送信息:
    client.Send(buffer);


  • 相关阅读:
    leetcode 131. Palindrome Partitioning
    leetcode 526. Beautiful Arrangement
    poj 1852 Ants
    leetcode 1219. Path with Maximum Gold
    leetcode 66. Plus One
    leetcode 43. Multiply Strings
    pytorch中torch.narrow()函数
    pytorch中的torch.repeat()函数与numpy.tile()
    leetcode 1051. Height Checker
    leetcode 561. Array Partition I
  • 原文地址:https://www.cnblogs.com/itrena/p/7434001.html
Copyright © 2011-2022 走看看