简体   繁体   English

C#TCP服务器进行简单聊天

[英]C# TCP Server for simple chat

I'm writing my first TCP server using Microsoft's supplied Async examples. 我正在使用Microsoft提供的Async示例编写第一台TCP服务器。

https://msdn.microsoft.com/en-us/library/fx6588te(v=vs.110).aspx https://msdn.microsoft.com/zh-CN/library/fx6588te(v=vs.110).aspx

I have everything working from the example. 我可以从示例中进行所有操作。 I am extending it as a simple chat program. 我将其扩展为一个简单的聊天程序。 But I am having trouble following the steps of this program (probably because of its async nature). 但是我在遵循该程序的步骤时遇到了麻烦(可能是由于其异步特性)。 When a message is received, it echoes back to the client and closes the socket. 收到消息后,它将回显到客户端并关闭套接字。 I do not see where it goes back to re-open the socket. 我看不到重新打开插座的位置。

public static void StartListening() {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // The DNS name of the computer
        // running the listener is "host.contoso.com".
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp );

        // Bind the socket to the local endpoint and listen for incoming connections.
        try {
            listener.Bind(localEndPoint);
            listener.Listen(100);

            while (true) {
                // Set the event to nonsignaled state.
                allDone.Reset();

                // Start an asynchronous socket to listen for connections.
                Console.WriteLine("Waiting for a connection...");
                listener.BeginAccept( 
                    new AsyncCallback(AcceptCallback),
                    listener );

                // Wait until a connection is made before continuing.
                allDone.WaitOne();
            }

        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();

    }

private static void SendCallback(IAsyncResult ar) {
        try {
            // Retrieve the socket from the state object.
            Socket handler = (Socket) ar.AsyncState;

            // Complete sending the data to the remote device.
            int bytesSent = handler.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to client.", bytesSent);

            handler.Shutdown(SocketShutdown.Both);
            handler.Close();

        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }

Also, is it not normal to leave the socket open? 另外,保持插座打开不正常吗?

When a message is received, it echoes back to the client and closes the socket. 收到消息后,它将回显到客户端并关闭套接字。 I do not see where it goes back to re-open the socket. 我看不到重新打开插座的位置。

That is because it doesn't. 那是因为事实并非如此。 The communication is done, the server receives, sends a reply and is done with that connection. 通信完成,服务器接收,发送答复,并完成该连接。 It just continues to wait for new connections on the listening socket. 它只是继续等待侦听套接字上的新连接。 You have a while (true). 您有一段时间(是)。 You'll keep waiting for new incoming connections in the accept call. 您将继续在accept呼叫中等待新的传入连接。 You'll get a new socket for each new client. 您将为每个新客户端获得一个新套接字。

Also, is it not normal to leave the socket open 另外,将插座打开是不正常的

Yes, the listening socket remains open. 是的,监听插槽保持打开状态。 It is kept open to keep on receiving new connections using accept 它保持打开状态以继续使用accept接收新连接

A better way to write a echo server using async and await can be found here : Using .Net 4.5 Async Feature for Socket Programming 可以在这里找到使用async和await编写回显服务器的更好方法: 使用.Net 4.5异步特性进行套接字编程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM