返回顶部

收藏

Socket监听简单示例

更多
static void Main(string[] args)
{
    var endPoint = new IPEndPoint(IPAddress.Loopback, 4444);        //监听本地端口 当应用启动时可在浏览器中访问<a href="http://localhost:4444">http://localhost:4444 或 <a href="http://127.0.0.1:4444">http://127.0.0.1:4444
    var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    socket.Bind(endPoint);  //绑定终结点
    socket.Listen(10);      //设置监听列队的长度

    while (true)
    {
        var client = socket.Accept();
        Console.WriteLine(client.RemoteEndPoint);

        var buffer = new byte[4069];

        var msgLength = client.Receive(buffer, 4069, SocketFlags.None);

        System.Text.UTF8Encoding utf = new UTF8Encoding();
        var receiveMsg = utf.GetString(buffer);

        Console.WriteLine("-----------收到的消息-----------\\r\\n{0}", receiveMsg); 

        //client.Send()
        break;
    }

    Console.Read();
}
//该片段来自于http://outofmemory.cn

标签:c#,.net,网络

收藏

0人收藏

支持

0

反对

0

发表评论