C# 多客户端服务器应用程序的问题

发布于 2024-10-09 20:41:14 字数 1670 浏览 4 评论 0原文

我有一个服务器应用程序和一个客户端应用程序。 我正在使用套接字在服务器和客户端之间进行通信。如果只有一个客户端连接,则一切正常:上传、下载一切正常。

但是,如果有另一个客户端连接(我再次启动客户端应用程序,这意味着我的计算机上运行着 2 个客户端应用程序和 1 个服务器应用程序),我的服务器就会开始混乱:服务器无法接收来自客户端、客户端的文件上传无法从服务器下载。

在服务器代码中,我已经对每个客户端连接使用了多线程,所以我无法找出问题所在。这是我的服务器代码:

    private void ServerForm_Load(object sender, System.EventArgs e)
            {

                //...
                Thread th = new Thread(new ThreadStart(ListenForPeers));
                th.Start();
            }

    public void ListenForPeers()
            {
                    serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    serversocket.Blocking = true;
                    IPHostEntry IPHost = Dns.GetHostEntry(server);
                    string[] aliases = IPHost.Aliases;
                    IPAddress[] addr = IPHost.AddressList;
                    IPEndPoint ipepServer = new IPEndPoint(addr[0], 8090);
                    serversocket.Bind(ipepServer);
                    serversocket.Listen(-1);
                    while (true)
                    {
                        clientsock = serversocket.Accept();
                        if (clientsock.Connected)
                        {
                            total_clients_connected++;
                            AppendText("Client connected...");
                            Thread tc = new Thread(new ThreadStart(listenclient));
                            tc.Start();
                        }
             }


    void listenclient()
        {
             // start communication
        }

我的服务器代码是否有问题,导致它无法成为多客户端服务器系统?非常感谢帮助。提前致谢。

I have a server application and a client application.
I'm using socket to communicate between server and client. Everything works fine if there's only one client connect: uploading, downloading all work well.

But if there's another client connect (I start the client application again, which means there're 2 client apps and 1 server app running on my computer), my server starts to mess up: server doesn't receive file upload from client, client couldn't download from server.

In server code, I already used multithreading for each client connection so I can't figure out the problem. Here is my server code:

    private void ServerForm_Load(object sender, System.EventArgs e)
            {

                //...
                Thread th = new Thread(new ThreadStart(ListenForPeers));
                th.Start();
            }

    public void ListenForPeers()
            {
                    serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    serversocket.Blocking = true;
                    IPHostEntry IPHost = Dns.GetHostEntry(server);
                    string[] aliases = IPHost.Aliases;
                    IPAddress[] addr = IPHost.AddressList;
                    IPEndPoint ipepServer = new IPEndPoint(addr[0], 8090);
                    serversocket.Bind(ipepServer);
                    serversocket.Listen(-1);
                    while (true)
                    {
                        clientsock = serversocket.Accept();
                        if (clientsock.Connected)
                        {
                            total_clients_connected++;
                            AppendText("Client connected...");
                            Thread tc = new Thread(new ThreadStart(listenclient));
                            tc.Start();
                        }
             }


    void listenclient()
        {
             // start communication
        }

Is there something wrong with my server code that makes it unable to become a multi-clients server system? Help is really appreciated. Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

彼岸花似海 2024-10-16 20:41:14

看起来您已将 clientSocket 定义为所有服务器线程使用的全局变量,而不是希望它成为每个线程的本地引用。您可以使用 ParameterizedThreadStart 来完成此操作:

public void listenForPeers()
{
  //Setup the server socket

  while(true){
    Socket newClient = serverSock.Accept();
    if(newClient.Connected){
      Thread tc = new Thread(new ParameterizedThreadStart(listenclient));
      tc.start(newClient);
    }
  }
}

void listenclient(object clientSockObj)
{
  Socket clientSock = (Socket)clientSockObj;

  //communication to client via clientSock.
}

It looks like you've defined your clientSocket as a global variable to be used by all server threads, instead you want it to be a local reference for each thread. You can do this with a ParameterizedThreadStart:

public void listenForPeers()
{
  //Setup the server socket

  while(true){
    Socket newClient = serverSock.Accept();
    if(newClient.Connected){
      Thread tc = new Thread(new ParameterizedThreadStart(listenclient));
      tc.start(newClient);
    }
  }
}

void listenclient(object clientSockObj)
{
  Socket clientSock = (Socket)clientSockObj;

  //communication to client via clientSock.
}
青萝楚歌 2024-10-16 20:41:14

首先,将套接字的 Blocking 属性设置为 true。这将阻止任何请求,直到前面的请求完成...

请参见此处:http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.blocking(VS.80).aspx

如果您处于阻止模式,并且您
进行一个不执行的方法调用
立即完成您的申请
将阻止执行,直到
请求的操作完成。如果你
希望继续执行,即使
请求的操作不是
完成后,更改 Blocking 属性
为假。 Blocking 属性没有
对异步方法的影响。如果你
正在发送和接收数据
异步并且想要阻塞
执行时,使用ManualResetEvent
类。

您可能需要重新考虑这样做,而是使用 WCF 或 Web 服务来上传文件...这会容易得多,并且 IIS 将为您处理线程。编写一个 Web 服务来上传文件非常容易...

http: //www.c-sharpcorner.com/UploadFile/scottlysle/UploadwithCSharpWS05032007121259PM/UploadwithCSharpWS.aspx

First, you're setting your socket's Blocking property to true. This will block any requests until the previous ones finish...

See here: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.blocking(VS.80).aspx

If you are in blocking mode, and you
make a method call which does not
complete immediately, your application
will block execution until the
requested operation completes. If you
want execution to continue even though
the requested operation is not
complete, change the Blocking property
to false. The Blocking property has no
effect on asynchronous methods. If you
are sending and receiving data
asynchronously and want to block
execution, use the ManualResetEvent
class.

You might want to reconsider doing it this way, and instead use WCF or maybe a web service for uploading the files... it'll be a lot easier, and IIS will handle the threading for you. It's pretty easy to write a web service to upload a file...

http://www.c-sharpcorner.com/UploadFile/scottlysle/UploadwithCSharpWS05032007121259PM/UploadwithCSharpWS.aspx

风吹过旳痕迹 2024-10-16 20:41:14

试试这个

const int noOfClients = 5;

for(int i=0;i<noOfClients;i++)
{
  Thread th = new Thread(new ThreadStart(ListenForPeers));
  th.Start();
}

try this

const int noOfClients = 5;

for(int i=0;i<noOfClients;i++)
{
  Thread th = new Thread(new ThreadStart(ListenForPeers));
  th.Start();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文