首页 > 解决方案 > TCPlistener server-client 和 client-server (从服务器向客户端发送消息)

问题描述

我想做的就是从服务器向客户端发送消息。我尝试了很多教程等,但仍然无法从服务器向客户端发送消息。从客户端发送到服务器很简单,并将其包含在代码中。当客户端向服务器发送“HI”时,我想向客户端响应 Hi。但不知道我应该在我的代码中添加什么。有人可以帮我吗?请不要像重复一样做我知道有很多类似的话题但找不到解决方案。

服务器代码:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
  IPAddress ip = Dns.GetHostEntry("localhost").AddressList[0];
  TcpListener server = new TcpListener(ip, Convert.ToInt32(8555));
  TcpClient client = default(TcpClient);
   try
   {
     server.Start();
     Console.WriteLine("Server started...");
   }
   catch (Exception ex)
   {
     Console.WriteLine(ex.ToString());
   };

   while (true)
   {
      client = server.AcceptTcpClient();
      byte[] receivetBuffer = new byte[100];
      NetworkStream stream = client.GetStream();
      stream.Read(receivetBuffer, 0, receivetBuffer.Length);
      StringBuilder msg = new StringBuilder();
      foreach(byte b in receivetBuffer)
      {
          if (b.Equals(59))
          {
            break;
          }
          else
          {
            msg.Append(Convert.ToChar(b).ToString());
          }
      }
       ////Resive message :
       if (msg.ToString() =="HI")
       {
          ///@EDIT 1
          ///// HERE Is SENDING  MESSAGE TO CLIENT//////////  
          int byteCount = Encoding.ASCII.GetByteCount("You said HI" + 1); 
          byte[] sendData = new byte[byteCount];
          sendData = Encoding.ASCII.GetBytes("You said HI" + ";");
          stream.Write(sendData, 0, sendData.Length); 
       }
}

客户端代码:

private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
   try
   {
     string serverIP = "localhost";
     int port = Convert.ToInt32(8555);
     TcpClient client = new TcpClient(serverIP, port);
     int byteCount = Encoding.ASCII.GetByteCount("HI"+ 1);
     byte[] sendData = new byte[byteCount];
     sendData = Encoding.ASCII.GetBytes("HI" + ";");
     NetworkStream stream = client.GetStream();
     stream.Write(sendData, 0, sendData.Length);


    ///////////////////////////////HERE I WANT A read message from server/
    /////////////////////////////////////////////////////////////////////

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

标签: c#socketstcplistener

解决方案


试试这个这是我的客户端和服务器版本,如果有任何参考问题,请随时询问,客户端等待服务器(在线)然后服务器是否在线连接。

连接服务器的方法

 private void Connectwithserver(ref TcpClient client)
    {
        try
        {
             //this is server ip and server listen port
            server = new TcpClient("192.168.100.7", 8080);
        }
        catch (SocketException ex)
        {
            //exceptionsobj.WriteException(ex);
            Thread.Sleep(TimeSpan.FromSeconds(10));
            RunBoTClient();

        }
    }

 byte[] data = new byte[1024];
    string stringData;
    TcpClient client;

    private void RunClient()
    {
         NetworkStream ns;
        Connectwithserver(ref client);

         while (true)
        {
            ns = client.GetStream();
            //old
            // ns.ReadTimeout = 50000;
            //old
            ns.ReadTimeout = 50000;
            ns.WriteTimeout = 50000;

            int recv = default(int);
            try
            {


                recv = ns.Read(data, 0, data.Length);


            }
            catch (Exception ex)
            {

                //exceptionsobj.WriteException(ex);
                Thread.Sleep(TimeSpan.FromSeconds(10));
               //try to reconnect if server not respond 
                RunClient();
            }
         //READ SERVER RESPONSE/MESSAGE
            stringData = Encoding.ASCII.GetString(data, 0, recv);
        }

    }

服务器

IPAddress localAdd = IPAddress.Parse(SERVER_IP);
    TcpListener listener = new TcpListener(localAdd, PORT_NO);
    Console.WriteLine("Listening...");
    listener.Start();
    while (true)
    {
        //---incoming client connected---
        TcpClient client = listener.AcceptTcpClient();

        //---get the incoming data through a network stream---
        NetworkStream nwStream = client.GetStream();
        byte[] buffer = new byte[client.ReceiveBufferSize];

        //---read incoming stream---
        int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

        //---convert the data received into a string---
        string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
        Console.WriteLine("Received : " + dataReceived);

         //IF YOU WANT TO WRITE BACK TO CLIENT USE
       string yourmessage = console.ReadLine();
        Byte[] sendBytes = Encoding.ASCII.GetBytes(yourmessage);
        //---write back the text to the client---
        Console.WriteLine("Sending back : " + yourmessage );
        nwStream.Write(sendBytes, 0, sendBytes.Length);
        client.Close();
    }
    listener.Stop();

推荐阅读