如何正确实现客户端服务器侦听器并根据传入的服务器数据更新ui

时间:2018-11-02 07:37:55

标签: c# sockets tcpclient

我正在尝试创建一个客户端,该客户端正在监听数据服务器并基于此更新ui。 只需单击按钮,客户端就应该能够向服务器等发送消息。

当单击连接按钮时,我创建一个serverListener线程,该线程正在连接到服务器并监听传入的数据(?)。

当客户端连接时,服务器向客户端发送数据(游戏状态),并基于此我试图更新Ui。(隐藏入口面板并显示大厅面板)。我不知道代码的正确性,但是直到那里运行正常,服务器向客户端发射gamestatus数据,并基于此隐藏gameEntrance面板并显示大厅面板。此外,我在serverListener中成功地从客户端向服务器发射userName数据。然后为了进行测试,我尝试通过使用从客户端向服务器发射数据在大厅面板中的trashButtonClick,但似乎我无法访问流,因此无法将数据发送到服务器。

NetworkStream stream = client.GetStream();//in trashbuttonclick

给出了System.ObjectDisposedException错误。

using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;



// This is the code for your desktop app.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.

namespace quizclient
{
    public partial class Form1 : Form
    {
        TcpClient client = new TcpClient();

        public Form1()
        {
            InitializeComponent();
            ipTextBox.Text = "127.0.0.1";
            portTextBox.Text = "8080";

        }





        private void Form1_Load(object sender, EventArgs e)
        {

        }
         async void serverListener(String ip,int port)
        {
            try
            {
                IPAddress IP = IPAddress.Parse(ip); 
        await client.ConnectAsync(IP, port); 

                if (client.Connected)
                {
                    NetworkStream stream = client.GetStream();
                    StringBuilder serverStringBuilder = new StringBuilder();
                    string serverString;
                    string clientString;

                    while (client.Connected)
                    {
                        byte[] buffer = new byte[client.ReceiveBufferSize];

                        int read = await stream.ReadAsync(buffer, 0, buffer.Length);
                        if (read > 0)
                        {
                            foreach(byte a in buffer)
                            {
                                if (a.Equals(00))
                                {
                                    break;
                                }
                                else
                                {
                                    serverStringBuilder.Append(Convert.ToChar(a).ToString());
                                }


                            }
                            serverString = serverStringBuilder.ToString();
                            if (serverString.All(char.IsDigit))
                            {

                                if (Convert.ToInt32(serverString) == 1)
                                {
                                    MessageBox.Show("Game has already started.You cant join.");
                                    break;
                                }
                                else if (Convert.ToInt32(serverString) == 0)
                                {

                                    clientString = "username:" + userNameTextBox.Text;
                                    this.Invoke((Action)delegate () // updating form this might be wrong
                                    {
                                        entrancePanel.Visible = false;
                                        lobbyPanel.Visible = true;
                                    });

                                    Console.WriteLine("sending username to server...");
                                    byte[] sendData = new byte[Encoding.ASCII.GetByteCount(clientString)];

                                    sendData = Encoding.ASCII.GetBytes(clientString);


                                    stream.Write(sendData, 0, sendData.Length);
                                }



                            }



                        }

                    }
                }
            }
            catch (Exception ex)
            {
                client.Close();
            }


        }

        private void connectButton_Click(object sender, EventArgs e)
        {

            string serverIp = ipTextBox.Text;
            Console.WriteLine(serverIp);
            int port;
            if (!int.TryParse(portTextBox.Text, out port))
            {
                // input wasn't parseable to an integer, show a message perhaps?
            }
            Console.WriteLine(port);
            string userName = userNameTextBox.Text;
            Thread t = new Thread(() => serverListener(serverIp,port));
            t.IsBackground = true;
            t.Start();




        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void trashButton_Click(object sender, EventArgs e)
        {

            NetworkStream stream = client.GetStream(); //crashes when i press this button.
            byte[] sendData = new byte[Encoding.ASCII.GetByteCount("testmessagefromclienttoserver")];

            sendData = Encoding.ASCII.GetBytes("testmessagefromclienttoserver");


            stream.Write(sendData, 0, sendData.Length);

        }
    }
}

0 个答案:

没有答案