C# 客户端服务器 TCP 客户端监听 [英] C# Client Server TCP Client Listening

查看:172
本文介绍了C# 客户端服务器 TCP 客户端监听的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段时间在编写 3D 代码,现在,我不想创建可与网络配合使用的游戏.我使用 System.Net 和 System.Net.Sockets.

I'm in coding 3D a while, and now, i wan't to create a game which works with Networking. I use the System.Net and System.Net.Sockets.

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

My Server is stupid as hell, it's just able to hold a single connection (later on, i will change it to multi-connection-abilities). It has a TcpListener which listens at 127.0.0.1 on Port 10000. (Just to test). In there, i have a DO While Loop which checks for received Data and Displays that.

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

My Client is a TcpClient. It connects to the Server and Sends a Message. Nothing special here, it's done with the TcpClient.GetStream().Write(). This works great. I'm also able to read one Answer right after the Send.

但是如果服务器会在没有客户端询问的情况下发送一些信息呢?例如:服务器上的所有玩家都会收到一个物品.我必须如何设置我的客户端才能接收此类消息?

But what if the Server will Send some infos without the Client's Asking? For Example: All Players on the Server receive an item. How do i have to set up my Client, to be able to receive such messages?

我的客户必须循环询问吗?还是我必须以某种方式委托?我可以创建一个循环,每 200 毫秒或其他时间询问此类信息,但这将如何改变 3D 游戏的性能?

Does my client have to ask in a loop? Or do i have to make a delegate somehow? I can create a loop which asks for such infos every 200 miliseconds or something, but how will this change the Performance of a 3D Game?

这在专业游戏开发中是如何完成的?

How is this done in Professional Game Developement?

推荐答案

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

Use the asynchronous capabilities of the TcpClient and TcpListener classes.
In your client:

private TcpClient server = new TcpClient();

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

这篇关于C# 客户端服务器 TCP 客户端监听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆