多客户端,一台服务器(发送对象)

编程入门 行业动态 更新时间:2024-10-10 04:23:49
本文介绍了多客户端,一台服务器(发送对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

好。我之前试过问这个问题,但不要以为我说的都是正确的。我目前有一个TCP服务器,可以接受无限量的客户端并发送数据字节(字符串)。我现在想要使用序列化等方法发送自定义对象。如何编写可以使用我的客户端代码(下面)并接受多个连接的服务器?我还需要服务器在收到对象后将对象发送给所有其他客户端,因此我需要在客户端保持连接打开。 这是我为序列化过程获得的代码: 客户端:

Okay. I've tried to ask this question before but don't think I've worded it correctly. I currently have a TCP server that can accept an unlimited amount of clients and send bytes of data (string). I now want to send custom objects using a method such as Serialization. How do I write a server that will work with my client side code (below) and accept multiple connections? I also need the server to send the object to all other clients once an object has been received so I will need to keep the connection open on client side. Here is the code I've got for the Serialization process: Client side:

Person p = new Person("Tyler", "Durden", 30); // create my serializable object string serverIp = "127.0.0.1"; TcpClient client = new TcpClient(serverIp, 9050); // have my connection established with a Tcp Server IFormatter formatter = new BinaryFormatter(); // the formatter that will serialize my object on my stream NetworkStream strm = client.GetStream(); // the stream formatter.Serialize(strm, p); // the serialization process strm.Close(); client.Close();

服务器端:

Server side:

TcpListener server = new TcpListener(9050); server.Start(); Console.WriteLine("Server ready"); TcpClient client = server.AcceptTcpClient(); NetworkStream strm = client.GetStream(); IFormatter formatter = new BinaryFormatter(); Person p = (Person)formatter.Deserialize(strm); // you have to cast the deserialized object Console.WriteLine("Hi, I'm " + p.FirstName); strm.Close(); client.Close();

所以我需要知道的是如何制作上面的代码,接受多个连接,让它们保持打开状态然后将所有收到的对象发送到所有连接的客户任何帮助都将不胜感激。

So what I need to know is how do I make the code above, accept multiple connections, keep them open and then send any received objects to all connected clients. Any help would be appreciated.

推荐答案

基本上,您的服务中至少需要两个独立的线程:一个接受新连接,另一个写入/读取网络流,用于根据您的应用层协议与所有已连接的客户端进行通信。请查看我过去的答案: 插座编程中的业余问题 [ ^ ], 来自同一端口号码的多个客户端 [ ^ ]。
-SA
Basically, you need a least two separate threads in your service: one accepting new connection, another one writing/reading to/from network stream for communication with all the already connected clients according to your application-layer protocol. Please see my past answers: an amateur question in socket programming[^], Multple clients from same port Number[^].
—SA

更多推荐

多客户端,一台服务器(发送对象)

本文发布于:2023-11-30 22:32:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651671.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:一台   客户端   对象   服务器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!