实例中的套接字客户端编程错误和服务器的回复

时间:2017-03-03 10:45:43

标签: c# multithreading sockets tcp-ip

我正在尝试创建一个基于TCP / IP的套接字编程,我试图在客户端和服务器之间建立连接。

我连接了硬件,我的服务器是我的表单和硬件设备之间的接口。

当我发送一些命令(ASCII值)时,服务器会响应。

我的服务器运行正常。

当我点击按钮时,即使我的客户端也连接到服务器,我也可以向服务器发送消息。

当我想从服务器接收消息时出现问题。

他们没有回应。

以下是我的代码:

public partial class Form1 : Form
{
    System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
    NetworkStream serverStream = default(NetworkStream);
    string readData = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void btnopen_Click(object sender, EventArgs e)
    {
        msg("Client Started");
        clientSocket.Connect("127.0.0.1", 11111);
        label1.Text = "Client Socket Program - Server Connected ...";
    }

    public void msg(string mesg)
    {
        textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        try
        {
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox1.Text + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }

    private void btnRecieve_Click(object sender, EventArgs e)
    {
        try
        {
            serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox1.Text + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
            Thread ctThread = new Thread(getMessage);
            ctThread.Start();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }

    private void getMessage()
    {
        while (true)
        {
            serverStream = clientSocket.GetStream();
            int buffSize = 0;
            byte[] inStream = new byte[10025];
            buffSize = clientSocket.ReceiveBufferSize;
            serverStream.Read(inStream, 0, buffSize);
            string returndata = System.Text.Encoding.ASCII.GetString(inStream);
            readData = "" + returndata;
            msg();
        }
    }

    private void msg()
    {
        if (this.InvokeRequired)
            this.Invoke(new MethodInvoker(msg));
        else
            textBox2.Text = textBox2.Text + Environment.NewLine + " >> " + readData;
    } 

    private void btnClose_Click(object sender, EventArgs e)
    {
        clientSocket.Close();
    } 
}

这是我的表单设计:

Form_Design

0 个答案:

没有答案