不能从客户端C#向服务器发送多个消息

时间:2019-02-26 22:31:41

标签: c# networking tcp client-server

我试图弄清楚如何从客户端向服务器控制台应用程序发送多个消息。每个打开的客户端应用程序都可以发送一条消息,然后单击下一个上的“发送”按钮后将冻结。

客户端也不会抛出任何异常或错误,它只是冻结直到强制关闭为止。

这是服务器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace server
{
    class Program
    {
        const int PORT = 8888;
        const string IP = "127.0.0.1";

        static void Main(string[] args)
        {
            //Create the TCP Listener
            TcpListener server = new TcpListener(IPAddress.Parse(IP), PORT);

            //Start the server
            server.Start();
            Console.WriteLine("> Server Started");

            //Server is always running
            while (true){
                //Accept clients connecting
                TcpClient clientSocket = server.AcceptTcpClient();
                NetworkStream serverStream = clientSocket.GetStream();

                //Read data from the stream and retrieve it
                string dataRead = ReadStream(serverStream, clientSocket);
                //Write to the network Stream the data recieved
                WriteStream(dataRead, serverStream);

            }
        }

        private static string ReadStream(NetworkStream serverStream, TcpClient clientSocket){
            //Create the Data Buffer
            byte[] buffer = new byte[clientSocket.ReceiveBufferSize];
            //Read the data from the network stream 
            int bytesRead = serverStream.Read(buffer, 0, clientSocket.ReceiveBufferSize);
            //Convert the bytesRead to string data
            string dataRead = Encoding.Unicode.GetString(buffer, 0, bytesRead);
            //print the data read to the console
            Console.WriteLine($"> {dataRead}");
            //Return the data read
            return dataRead;
        }

        private static void WriteStream(string dataWrite, NetworkStream serverStream){
            //Pack the string into a data buffer
            byte[] buffer = Encoding.Unicode.GetBytes(dataWrite);
            //Determine the amount of bytes to send
            int bytesWrite = Encoding.Unicode.GetByteCount(dataWrite);
            //Write to the network stream
            serverStream.Write(buffer, 0, bytesWrite);
        }
    }
}

这是客户端应用程序,它是Windows窗体应用程序:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace client
{
    public partial class Form1 : Form
    {
        const int PORT = 8888;
        const string IP = "127.0.0.1";
        TcpClient client;
        NetworkStream serverStream;
        bool isConnected = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void Btn_Connect_Click(object sender, EventArgs e)
        {            
            //Create the client at the specified IP and PORT
            client = new TcpClient(IP, PORT);
            //Display Connected Message to Textbox
            if (!isConnected) Tbx_Chat.Text += $">Connected to {IP}:{PORT}{Environment.NewLine}";
            isConnected = true;

            //Create the serverStream
            serverStream = client.GetStream();
        }

        private void Btn_Send_Click(object sender, EventArgs e)
        {
            //Send data to the serverStream
            WriteData(serverStream, $"{Tbx_Name.Text}: {Tbx_Main.Text}");

            //read data from stream and save to textbox
            Tbx_Chat.Text += $">{ReadData(client, serverStream)}{Environment.NewLine}";
        }

        private static string ReadData(TcpClient client, NetworkStream serverStream){
            //Create the data buffer
            byte[] byteRead = new byte[client.ReceiveBufferSize];
            //Read data from network stream
            int bytesRead = serverStream.Read(byteRead, 0, client.ReceiveBufferSize);
            //Convert data read to string data and return
            string dataRead = Encoding.Unicode.GetString(byteRead, 0, bytesRead);
            return dataRead;
        }

        private static void WriteData(NetworkStream serverStream, string dataSend){
            //Create the data to send in the form of a byte array
            byte[] byteSend = Encoding.Unicode.GetBytes(dataSend);
            //Write to the server stream
            serverStream.Write(byteSend, 0, byteSend.Length);
        }
    }
}

0 个答案:

没有答案