多客户端,一台服务器(发送对象) [英] Multi client, one server (Sending objects)

查看:69
本文介绍了多客户端,一台服务器(发送对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好。我之前试过问这个问题,但不要以为我说的都是正确的。我目前有一个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.

推荐答案

基本上,您的服务中至少需要两个独立的线程:一个接受新连接,另一个写入/读取网络流,用于根据您的应用层协议与所有已连接的客户端进行通信。请查看我过去的答案:

插座编程中的业余问题 [< a href =http://www.codeproject.com/Answers/536542/anplusamateurplusquestionplusinplussocketplusprogr#answer2target =_ blanktitle =New Window> ^ ],

< a href =http://www.codeproject.com/Answers/165297/Multple-clients-from-same-port-Number#answer1>来自同一端口号码的多个客户端 [ ^ ]。



-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


这篇关于多客户端,一台服务器(发送对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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