问题 如何确保从服务器向客户端发送多个串行数据

pooya1072

新成员
已加入
2019年4月23日
留言内容
1
编程经验
1-3
我的程序分为两部分,服务器和客户端。当客户端连接到服务器时,此时,服务器应向客户端发送数字1到10。但只会发送一个或两个第一个号码。
这是服务器端:在AcceptClient子目录中,我创建一个for循环,以将数字1到10发送给客户端。
Server side code:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Module1
{
    private static TcpClient pClient;
    private static TcpListener Listener;
    private static System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);

    static void Main()
    {
        mre.Reset();
        Listener = new TcpListener(IPAddress.Any, 6000);
        Listener.Start();
        Console.WriteLine("SERVER : Server is start ...");
        Listener.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), Listener);
        mre.WaitOne();
    }

    static void AcceptClient(IAsyncResult ar)
    {
        pClient = Listener.EndAcceptTcpClient(ar);
        Listener.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), Listener);
        for (int i = 1; (i <= 10); i++)
        {
            Module1.Send(i.ToString());
        }

    }

    public static void Send(string Messsage)
    {
        StreamWriter sendMessage = new StreamWriter(pClient.GetStream());
        sendMessage.WriteLine(Messsage);
        sendMessage.Flush();
    }
}
Client side code:
using System;
using System.IO;
using System.Net.Sockets;
class Module1
{
    private static TcpClient client;
    private static System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);

    static void Main()
    {
        mre.Reset();
        try
        {
            client = new TcpClient("localhost", 6000);
            Console.WriteLine("CLIENT : client is connected ...");
            client.GetStream().BeginRead(new byte[] { 0 }, 0, 0, new AsyncCallback(read), client.GetStream());
        }
        catch (Exception ex)
        {
            Console.WriteLine("CLIENT : " + ex.Message);
        }
        mre.WaitOne();
    }

    static void read(IAsyncResult ar)
    {
        try
        {
            NetworkStream ns = (NetworkStream) ar.AsyncState;
            Int16 l = (Int16)ns.EndRead(ar);
            string msg = (new StreamReader(client.GetStream()).ReadLine());
            Console.WriteLine(msg);
            ns.BeginRead(new byte[] { 0 }, 0, 0, new AsyncCallback(read), ns);
        }
        catch (Exception ex)
        {
            Console.WriteLine("CLIENT : " + ex.Message);
            return;
        }
    }
}

在单独的控制台中运行每一端,然后首先运行服务器端。
我想知道如何更正此代码以发送所有这些号码?
 
Last edited:

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,540
地点
弗吉尼亚州切萨皮克
编程经验
10+
Your server code is not thread safe. You have only one pClient in a static class variable. What happens when two connections or more connections are accepted near simultaneously and the execution of 接受Client() and or Send() overlap each other?
 
最佳 底部