-1

这是服务器上的代码(C#):

private void Form1_Load(object sender, EventArgs e)
    {
        Thread service = new Thread((ThreadStart)delegate
        {
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");
            TcpListener listener = new TcpListener(localAddr, 13235);
            listener.Start();
            Console.Write("Waiting for a connection... ");
            TcpClient client = listener.AcceptTcpClient();
            Console.WriteLine("Connected!");
            NetworkStream str = client.GetStream();
            byte[] bytes5 = new byte[client.ReceiveBufferSize];


            str.Read(bytes5, 0, (int)client.ReceiveBufferSize);
            string returndata = Encoding.UTF8.GetString(bytes5);

            Console.WriteLine("ewwww hone :" + returndata);
            label1.Text = returndata;
            client.Close();

        });
        service.Start();

    }

}

Java 客户端:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    DataOutputStream os = null;
    DataInputStream is = null;
    int port = 13235;

    System.out.println("SocketClient initialized \n");
    try {
        InetAddress address = InetAddress.getByName("127.0.0.1");

        Socket connection = new Socket(address, port);
        os = new DataOutputStream(connection.getOutputStream());
        is = new DataInputStream(connection.getInputStream());
        os.writeBytes(jTextField1.getText()); 

        System.out.println(jTextField1.getText());
    }
    catch (IOException f) {
        System.out.println("IOException: " + f);
    }
    catch (Exception g) {
        System.out.println("Exception: " + g);
    }
}

我的程序只有在我第一次单击按钮时才能正常工作,但在那之后我什么也没有得到!知道如何解决它,或者有什么问题吗?我需要的是我点击那个按钮(在客户端)我需要在服务器端得到它......

4

3 回答 3

2

看看TcpListenerMSDN 上的示例代码:http: //msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx

您缺少while代码中的循环。第一次连接后,它调用.close()然后退出你的线程。它应该循环回来开始监听下一个连接。

于 2013-05-11T00:54:09.240 回答
1

似乎您没有关闭连接/流,并且在第二次单击时您再次打开套接字连接。您可以在每次单击时关闭套接字连接。或者您保持套接字打开,并且每次单击时都不要重新初始化它。

于 2013-05-11T00:24:01.607 回答
0

You need to put your reading and writing stream code within a while loop to read/write multiple times.

于 2013-05-21T14:32:07.543 回答