用于简单聊天的 C# TCP 服务器

标签 c# sockets tcp

我正在使用 Microsoft 提供的异步示例编写我的第一个 TCP 服务器。

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

示例中的所有内容均有效。我将其扩展为一个简单的聊天程序。但是我在执行这个程序的步骤时遇到了麻烦(可能是因为它的异步性质)。收到消息后,它会回显给客户端并关闭套接字。我看不到它返回到哪里重新打开套接字。

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());
        }
    }

另外,socket一直开着不是很正常吗?

最佳答案

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.

那是因为它没有。通信完成,服务器接收、发送回复并完成该连接。它只是继续等待监听套接字上的新连接。你有一段时间(真的)。您将在接听电话中继续等待新的传入连接。您将为每个新客户端获得一个新套接字。

Also, is it not normal to leave the socket open

是的,监听套接字保持打开状态。它保持打开状态以继续使用 accept 接收新连接

可以在这里找到使用异步和等待编写回显服务器的更好方法:Using .Net 4.5 Async Feature for Socket Programming

关于用于简单聊天的 C# TCP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31895500/

相关文章:

c# - 使用被忽略的属性的 QueryOver

c - C中的服务器客户端程序

c - C语言中的套接字和线程段错误

networking - 为什么UDP+软件可靠点餐系统比TCP快?

c# - 用于读取和解码 SSL 消息的循环不起作用

c# - 如何在 C# 中使用线程一次发送多个 Web 请求?

c# - 如何为 IsChecked 属性设置动画?

c# - 基于项目属性的网格背景颜色

java - 多线程客户端/服务器应用程序java问题

Spring集成TCP,强制重连