c# - 通过Tcp/IP将客户端数据Queue发送到服务器端

标签 c# sockets tcp client-server binary-serialization

我想从客户端向服务器发送数据。有两个队列。在客户端和服务器端。我想让我的客户端连接到服务器并将客户端队列中的所有数据发送到服务器。在服务器端我想接受所有客户端并获取所有对象并添加到服务器端队列

客户端代码:

Queue<Person> clientQueue;   // This is the client side queue

IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 15884);
var client = new TcpClient();

while(!clientQueue.IsEmpty)
{
    Person personObj = clientQueue.Dequeue();

    client.Connect(serverEndPoint);
    NetworkStream clientStream = client.GetStream();
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(clientStream, personObj);
    clientStream.Flush();
}

服务器端:

Queue<Person> serverQueue;   // This is the server side queue

IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 15884);
TcpListener tcpListener = new TcpListener(ipEndPoint);


while(true)
{
    TcpClient client = tcpListener.AcceptTcpClient();
    NetworkStream clientStream = tcpClient.GetStream();
    BinaryFormatter bf = new BinaryFormatter();
    Person person = (Person)bf.Deserialize(clientStream);
    tcpClient.Close();

    serverQueue.Enqueue(person);
}

我知道上面的代码不起作用。我只想画出我的设计草图。有人可以把代码示例发给我吗?如何将客户端队列发送到服务器队列..

谢谢..

最佳答案

  1. 如果您使用的是 .net 4.0,对于服务器端和客户端的队列,您应该使用 BlockingCollection,对于早期版本,请结合使用队列AutoResetEvent。检查this .

  2. 在服务器端,您应该使用异步方法或只实例化一个新线程来处理每个新客户端,然后在该线程读取数据。喜欢:

    TcpClient client = tcpListener.AcceptTcpClient();
    ThreadPool.QueueUserWorkItem(new WaitHandle(HandleCleint), client);
    
    private void HandleClient(object clientObject)
    {
        TcpClient client = (TcpClient)clientObject;
        NetworkStream clientStream = client.GetStream();
        //handle the data here
    }
    

编辑:您在评论中声明:

I don't have an idea about how to change my program to send an entire queue to server side

数组或队列本身是一个对象:

//at your client side:
bf.Serialize(clientStream, persons);//assume persons is Queue<Person>

//at your server side:
Queue<Person> persons = (Queue<Person>)bf.Deserialize(clientStream);

关于c# - 通过Tcp/IP将客户端数据Queue发送到服务器端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6798979/

相关文章:

java - Android 线程因未知原因停止

c# - 如何在不单击 C# 中的按钮的情况下直接从 TCP/IP 消息传递中的服务器接收文本?

c# - 将 Microsoft.Graph 与控制台应用程序结合使用

java - 如何向服务器验证我的 XMPP 客户端?

c - C 中的套接字,带有 select() 方法的非阻塞 send() 和 receive()

linux - 一个socket fd已经调用了 "shutdown",我可以 "reopen"吗?

c++ - 创建套接字 C++

c# - 在第二部分和第三部分中输入低于 "An invalid IP address was specified"的数字时出现错误 "100"

c# - 为什么 (WPF) 窗口不是 0.0 像素宽?

c# - 使用平均核的图像处理