3

I was about making client server string sending and receiving using networkstream. and I want to replace 1000 client into one application using thread and thread.join. But i cannot solve this problem. Thanks for the reply.

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);
        }
    }
}
4

1 回答 1

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...
             }));
        }
    }

然后阅读有关线程同步的信息;)。

于 2012-11-05T11:52:38.533 回答