C#客户端服务器TCP客户端侦听

时间:2013-12-20 09:37:13

标签: c# tcp client-server

我正在编写3D代码,现在,我不想创建一个适用于网络的游戏。我使用System.Net和System.Net.Sockets。

我的服务器很愚蠢,它只能保持一个连接(稍后,我会将其更改为多连接功能)。它有一个TcpListener,它在端口10000上侦听127.0.0.1。(只是为了测试)。在那里,我有一个DO While循环,它检查接收到的数据并显示它。

我的客户端是TcpClient。它连接到服务器并发送消息。这里没什么特别的,它是用TcpClient.GetStream()完成的.Write()。这非常有效。我也可以在发送后立即阅读一个答案。

但是如果服务器在没有客户端询问的情况下发送一些信息怎么办?例如:服务器上的所有玩家都会收到一个项目。我如何设置我的客户端,以便能够接收此类消息?

我的客户是否必须循环询问?或者我必须以某种方式成为代表?我可以创建一个循环,每200毫秒或者其他东西要求这样的信息,但这将如何改变3D游戏的性能?

如何在专业游戏开发中完成这项工作?

2 个答案:

答案 0 :(得分:0)

使用异步客户端套接字:

  

“客户端是用异步套接字构建的,所以执行   服务器返回时,客户端应用程序未挂起   响应“。

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

private static void ReceiveCallback( IAsyncResult ar ) {
        try {
            // Retrieve the state object and the client socket 
            // from the asynchronous state object.
            StateObject state = (StateObject) ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0) {
                // There might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));

                // Get the rest of the data.
                client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
                    new AsyncCallback(ReceiveCallback), state);
            } else {
                // All the data has arrived; put it in response.
                if (state.sb.Length > 1) {
                    response = state.sb.ToString();
                }
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }

在此ReceiveCallback中,您可以创建一个处理服务器消息的开关。

例如: 消息的第一个字节是命令,命令后是正确的数据。在交换机中,您可以处理该命令并执行一些代码。

答案 1 :(得分:0)

使用TcpClient和TcpListener类的异步功能 在您的客户中:

private TcpClient server = new TcpClient();

void listen(){
    try {
        IPAddress IP = IPAddress.Loopback // this is your localhost IP
        await server.ConnectAsync(IP,10000); // IP, port number

        if(server.Connected) {
           NetworkStream stream = server.GetStream();

           while (server.Connected) {
               byte[ ] buffer = new byte[server.ReceiveBufferSize];
               int read = await stream.ReadAsync(buffer, 0, buffer.Length);
               if (read > 0 ){
                    // you have received a message, do something with it
               }
           }
        }
    }
    catch (Exception ex) {
         // display the error message or whatever
         server.Close();
    }
}