.NET Socket收发数据

在发送数据之前,首发双方约定好统一的端口,数据起始符、结束符

Socket 通过单一信道进行收发数据

 

class Program
{
    static void Main(string[] args)
    {
         ServerController.Listen(8888);

        string data = "我真帅";
        string result = ServerController.Send("127.0.0.1", 8888, data);
        Console.WriteLine("Send:{0}\r\nReceive:{1}", data, result);
        Console.ReadKey();
    }
}

`</pre>
</div>
<div>
<div>
<pre>`public class ServerController //: Controller
{
    /*数据的开始结束符号*/

    /// &lt;summary&gt;
    /// 编码 解码
    /// &lt;/summary&gt;
    private static Encoding encode = Encoding.Default;

    /// &lt;summary&gt;
    /// 监听请求
    /// &lt;/summary&gt;
    /// &lt;param name="port"&gt;端口&lt;/param&gt;
    public static void Listen(int port)
    {

        //IPv4  双向基于连接的字节流  传输控制协议
        Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        // 将Socket与本地端点相关联
        listenSocket.Bind(new IPEndPoint(IPAddress.Any, port));
        // 挂起连接队列的最大长度
        listenSocket.Listen(100);
        Console.WriteLine("Listen " + port + " ...");
        //循环监听
        while (true)
        {
            //未接收,则一直阻塞
            Socket acceptSocket = listenSocket.Accept();
            try
            {
                //1s timeout.
                string receiveData = Receive(acceptSocket, 1000); 
                Console.WriteLine("Receive:" + receiveData);
                //发送接受状态
                Send(acceptSocket, "ok");
            }
            catch (Exception e)
            {
                //发送接受状态
                Send(acceptSocket, "failed");
                Console.WriteLine(e);
            }

            DestroySocket(acceptSocket); //import
        }
    }

    /// &lt;summary&gt;
    /// 发送数据
    /// &lt;/summary&gt;
    /// &lt;param name="host"&gt;主机名 IP&lt;/param&gt;
    /// &lt;param name="port"&gt;端口&lt;/param&gt;
    /// &lt;param name="data"&gt;数据&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public static string Send(string host, int port, string data)
    {

        string result = string.Empty;
        Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            //建立与远程hos的连接
            clientSocket.Connect(host, port);
            ////发送数据
            //clientSocket.Send(encode.GetBytes(data));
            //发送数据data
            Send(clientSocket, data);
            //等待2秒
            result = Receive(clientSocket, 1000 * 2); //1*2 seconds timeout.
            //销毁socket
        }
        catch (Exception e)
        {
            Console.WriteLine("由于目标计算机积极拒绝,无法连接" + e);
        }

        DestroySocket(clientSocket);
        //Console.WriteLine("Send:{0}\r\nReceive:{1}", data, result);

        return result;
    }

    /// &lt;summary&gt;
    /// 发送数据
    /// &lt;/summary&gt;
    /// &lt;param name="socket"&gt;socket&lt;/param&gt;
    /// &lt;param name="data"&gt;数据&lt;/param&gt;
    private static void Send(Socket socket, string data)
    {
        //字符编码为字节序列,然后发送
        socket.Send(encode.GetBytes(data));
    }

    /// &lt;summary&gt;
    /// 接收数据
    /// &lt;/summary&gt;
    /// &lt;param name="socket"&gt;&lt;/param&gt;
    /// &lt;param name="timeout"&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public static string Receive(Socket socket, int timeout)
    {
        string result = string.Empty;
        // 超时
        socket.ReceiveTimeout = timeout;
        List&lt;byte&gt; data = new List&lt;byte&gt;();
        byte[] buffer = new byte[1024];
        try
        {
            //1.若缓冲区buffer比接收数据小,需多次Receive才能完成;
            //2.多次Receive时,每次接收字节数length大小不固定;
            //3.实际接收字节数据
            int length = 0;
            //循环接收数据到接收缓冲区
            while ((length = socket.Receive(buffer)) &gt; 0)
            {
                for (int j = 0; j &lt; length; j++)
                {
                    data.Add(buffer[j]);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        if (data.Count &gt; 0)
        {
            //字节转化为字符
            result = encode.GetString(data.ToArray(), 0, data.Count);
        }

        return result;
    }

    /// &lt;summary&gt;
    /// 销毁Socket对象
    /// &lt;/summary&gt;
    /// &lt;param name="socket"&gt;&lt;/param&gt;
    private static void DestroySocket(Socket socket)
    {
        try
        {
            if (socket != null)
            {
                if (socket.Connected)
                {
                    socket.Shutdown(SocketShutdown.Both);
                }
                socket.Close();
            }
            Console.WriteLine("Socket销毁成功");
        }
        catch (Exception e)
        {
            Console.WriteLine("Socket销毁失败" + e);
            throw;
        }

    }
}



https://msdn.microsoft.com/en-us/library/system.net.sockets.socket(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/2b86d684(v=vs.110).aspx

https://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket_methods(v=vs.80).aspx

文章目录
|