多线程客户端向服务器发送突发字符串

时间:2012-11-05 07:23:43

标签: c# multithreading client-server

我是关于使用networkstream进行客户端服务器字符串发送和接收。我想使用thread和thread.join将1000客户端替换为一个应用程序。但我无法解决这个问题。谢谢你的回复。

private void button1_Click(object sender, RoutedEventArgs e)
    {
        sc = new SocketMe();
        sc.socketStart();
        for (int i = 0; i < 10; i++)
        {
            //sc = new SocketMe();
            //this.Dispatcher.Invoke((Action)(() =>
            //{
            nomor[i] = new Thread(sc.execution);
            nomor[i].Start(10);
            //}));
        }
    }
public class SocketMe
{
    public NetworkStream serverStream; 
    MainWindow mw = new MainWindow();
    public void socketStart()
    {
        mw.clientSocket = new TcpClient();
        try
        {
            mw.clientSocket.Connect("localhost", 4000);
        }
        catch (Exception e)
        {
            //mw.label3.Content = "Error ...." + e.StackTrace;
        }
    }
    public void StringtoSend(String x)
    {
        try
        {
            socketStart();
            serverStream = mw.clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(x);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            byte[] inStream = new byte[10025];
            serverStream.Read(inStream, 0, (int)mw.clientSocket.ReceiveBufferSize);
            string returndata = System.Text.Encoding.ASCII.GetString(inStream);
            //textBox2.Text = "Data from Server : " + returndata;
            Console.WriteLine("Data from Server : " + returndata); 
        }
        catch (Exception ex)
        {
            //mw.label3.Content = ex.StackTrace;
        }
    }
    public void execution(object data)
    {
        socketStart();
        string[] pertanyaan = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ,"'{0}'"};//isi one dengan pertanyaan-pertanyaan yang diinginkan
        int i;
        for (i = 0; i < 10; i++)
        {
            StringtoSend(pertanyaan[i]);
            Thread.Sleep(1000);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您正在从10个线程访问相同的功能而没有同步! 试试这个(只是为了好玩):

private void button1_Click(object sender, RoutedEventArgs e)
    {
        for (int i = 0; i < 10; i++)
        {

             this.Dispatcher.BeginInvoke((Action)(() =>
             {
                 SocketMe sc = new SocketMe();
                 sc.socketStart();
                 // etc...
             }));
        }
    }

然后阅读线程同步;)。