【问题标题】:Server Client send/receive simple text服务器客户端发送/接收简单文本
【发布时间】:2012-04-28 07:00:38
【问题描述】:

我有一个作业来构建一个应用程序,它将在服务器和客户端之间发送和接收简单的字符串。我知道如何建立连接,但不知道如何发送和接收字符串。这是我的代码:

public partial class Form1 : Form
{
    private Thread n_server;
    private Thread n_client;
    private Thread n_send_server;
    private TcpClient client;
    private TcpListener listener;
    private int port = 2222;
    private string IP = " ";
    private Socket socket;
    public Form1()
    {
        InitializeComponent();
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    public void Server()
    {
        listener = new TcpListener(IPAddress.Any, port);
        listener.Start();
        try
        {
            socket = listener.AcceptSocket();
            if (socket.Connected)
            {
                textBox2.Invoke((MethodInvoker)delegate { textBox2.Text = "Client : " + socket.RemoteEndPoint.ToString(); });
            }
        }
        catch
        {
        }
    }

    public void Client()
    {
        IP = "localhost";
        client = new TcpClient();
        try
        {
            client.Connect(IP, port);
        }

        catch (Exception ex)
        {
            MessageBox.Show("Error : " + ex.Message);
        }

        if (client.Connected)
        {
            textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Connected..."; });

        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        n_server = new Thread(new ThreadStart(Server)); 
        n_server.IsBackground = true;
        n_server.Start();
        textBox1.Text = "Server up";
    }

    private void button2_Click(object sender, EventArgs e)
    {
        n_client = new Thread(new ThreadStart(Client));
        n_client.IsBackground = true;
        n_client.Start();
    }

    private void send()
    {
        // I want to use this method for both buttons : "send button" on server side    and "send button"
        // on client side. First I read text from textbox2 on server side or textbox3
        // on client side than accept and write the string to label2(s) or label3(c).
        // 
    }


    private void button3_Click(object sender, EventArgs e)
    {
        n_send_server = new Thread(new ThreadStart(send));
        n_send_server.IsBackground = true;
        n_send_server.Start();
    }
}

【问题讨论】:

    标签: c# .net winforms sockets


    【解决方案1】:

    以下代码向服务器发送和接收当前日期和时间

    //以下代码用于服务器应用程序:

    namespace Server
    {
        class Program
        {
            const int PORT_NO = 5000;
            const string SERVER_IP = "127.0.0.1";
    
            static void Main(string[] args)
            {
                //---listen at the specified IP and port no.---
                IPAddress localAdd = IPAddress.Parse(SERVER_IP);
                TcpListener listener = new TcpListener(localAdd, PORT_NO);
                Console.WriteLine("Listening...");
                listener.Start();
    
                //---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);
    
                //---write back the text to the client---
                Console.WriteLine("Sending back : " + dataReceived);
                nwStream.Write(buffer, 0, bytesRead);
                client.Close();
                listener.Stop();
                Console.ReadLine();
            }
        }
    }
    

    //这是客户端的代码

    namespace Client
    {
        class Program
        {
            const int PORT_NO = 5000;
            const string SERVER_IP = "127.0.0.1";
            static void Main(string[] args)
            {
                //---data to send to the server---
                string textToSend = DateTime.Now.ToString();
    
                //---create a TCPClient object at the IP and port no.---
                TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
                NetworkStream nwStream = client.GetStream();
                byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
    
                //---send the text---
                Console.WriteLine("Sending : " + textToSend);
                nwStream.Write(bytesToSend, 0, bytesToSend.Length);
    
                //---read back the text---
                byte[] bytesToRead = new byte[client.ReceiveBufferSize];
                int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
                Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
                Console.ReadLine();
                client.Close();
            }
        }
    }
    

    【讨论】:

    • 嗨@SANDEEP,代码就像一个魅力。我在提交之前测试过。
    • 为什么只能读取服务器返回的第一条消息?下次我调用 nwStream.Read 时,它不会返回任何值。当我设置调试点时,我无法进入下一行,没有抛出异常。
    • 服务器端有什么例子,消息如何处理?如果服务器得到 1 来运行 function1 和 returen1 如果他得到 2 什么都不做等等?
    【解决方案2】:
        static void Main(string[] args)
        {
            //---listen at the specified IP and port no.---
            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);
    
                //---write back the text to the client---
                Console.WriteLine("Sending back : " + dataReceived);
                nwStream.Write(buffer, 0, bytesRead);
                client.Close();
            }
            listener.Stop();
            Console.ReadLine();
        }
    

    除了@Nudier Mena 回答之外,还保留一个while 循环以保持服务器处于侦听模式。这样我们就可以连接多个客户端实例。

    【讨论】:

      【解决方案3】:
         public partial class Form1 : Form
          {
              private Thread n_server;
              private Thread n_client;
              private Thread n_send_server;
              private TcpClient client;
              private TcpListener listener;
              private int port = 2222;
              private string IP = " ";
              private Socket socket;
              byte[] bufferReceive = new byte[4096];
              byte[] bufferSend = new byte[4096];
              public Form1()
              {
                  InitializeComponent();
              }
      
              private void exitToolStripMenuItem_Click(object sender, EventArgs e)
              {
                  Application.Exit();
              }
      
              public void Server()
              {
                  listener = new TcpListener(IPAddress.Any, port);
                  listener.Start();
                  try
                  {
                      socket = listener.AcceptSocket();
                      if (socket.Connected)
                      {
                          textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Client        : " + socket.RemoteEndPoint.ToString(); });
                      }
                      while (true)
                      {
                          int length = socket.Receive(bufferReceive);
                          if (length > 0)
                          {
                              label2.Invoke((MethodInvoker)delegate { label2.Text = Encoding.Unicode.GetString(bufferReceive); });
                          }
                      }
                  }
                  catch
                  {
                  }
              }
      
              public void Client()
              {
                  IP = "localhost";
                  client = new TcpClient();
                  try
                  {
                      client.Connect(IP, port);
                      while (true)
                      {
                          NetworkStream nts = client.GetStream();
                          int length;
                          while ((length = nts.Read(bufferReceive, 0, bufferReceive.Length)) != 0)
                          {
                             label3.Invoke((MethodInvoker)delegate { label3.Text = Encoding.Unicode.GetString(bufferReceive); });
                          }
                      }
                  }
      
                  catch (Exception ex)
                  {
                      MessageBox.Show("Error : " + ex.Message);
                  }
      
                  if (client.Connected)
                  {
                      textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Connected..."; });
      
                  }
              }
      
              private void button1_Click(object sender, EventArgs e)
              {
                  n_server = new Thread(new ThreadStart(Server));
                  n_server.IsBackground = true;
                  n_server.Start();
                  textBox1.Text = "Server up";
              }
      
              private void button2_Click(object sender, EventArgs e)
              {
                  n_client = new Thread(new ThreadStart(Client));
                  n_client.IsBackground = true;
                  n_client.Start();
              }
      
              private void send()
              {
                  if (socket!=null)
                  {
                      bufferSend = Encoding.Unicode.GetBytes(textBox2.Text);
                      socket.Send(bufferSend);
                  }
                  else
                  {
                      if (client.Connected)
                      {
                          bufferSend = Encoding.Unicode.GetBytes(textBox3.Text);
                          NetworkStream nts = client.GetStream();
                          if (nts.CanWrite)
                          {
                              nts.Write(bufferSend,0,bufferSend.Length);
                          }
      
                      }
                  }
              }
      
      
      
              private void button3_Click(object sender, EventArgs e)
              {
                  n_send_server = new Thread(new ThreadStart(send));
                  n_send_server.IsBackground = true;
                  n_send_server.Start();
              }
          }
      

      【讨论】:

        【解决方案4】:
        bool SendReceiveTCP(string ipAddress, string sendMsg, ref string recMsg)
            {
                try
                {
                    DateTime startTime=new DateTime();
                    TcpClient clt = new TcpClient();
                    clt.Connect(ipAddress, 8001);
                    NetworkStream nts = clt.GetStream();
                    nts.Write(Encoding.ASCII.GetBytes(sendMsg),0, sendMsg.Length);
                    startTime = DateTime.Now;
                    while (true)
                    {
                        if (nts.DataAvailable)
                        {
                            byte[] tmpBuff = new byte[1024];
                            System.Threading.Thread.Sleep(100);
                            int readOut=nts.Read(tmpBuff, 0, 1024);
                            if (readOut > 0)
                            {
                                recMsg = Encoding.ASCII.GetString(tmpBuff, 0, readOut);
                                nts.Close();
                                clt.Close();
                                return true;
                            }
                            else
                            {
                                nts.Close();
                                clt.Close();
                                return false;
                            }
                        }
                        TimeSpan tps = DateTime.Now - startTime;
                        if (tps.TotalMilliseconds > 2000)
                        {
                            nts.Close();
                            clt.Close();
                            return false;
                        }
                        System.Threading.Thread.Sleep(50);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        

        【讨论】:

        • 欢迎来到 Stack Overflow!虽然这段代码可以解决问题,including an explanation 解决问题的方式和原因确实有助于提高帖子的质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的答案以添加解释并说明适用的限制和假设。 From Review
        【解决方案5】:

        客户

        namespace SocketKlient
        
        {
            class Program
        
            {
                static Socket Klient;
                static IPEndPoint endPoint;
                static void Main(string[] args)
                {
                    Klient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    string command;
                    Console.WriteLine("Write IP address");
                    command = Console.ReadLine();
                    IPAddress Address;
                    while(!IPAddress.TryParse(command, out Address)) 
                    {
                        Console.WriteLine("wrong IP format");
                        command = Console.ReadLine();
                    }
                    Console.WriteLine("Write port");
                    command = Console.ReadLine();
        
                    int port;
                    while (!int.TryParse(command, out port) && port > 0)
                    {
                        Console.WriteLine("Wrong port number");
                        command = Console.ReadLine();
                    }
                    endPoint = new IPEndPoint(Address, port); 
                    ConnectC(Address, port);
                    while(Klient.Connected)
                    {
                        Console.ReadLine();
                        Odesli();
                    }
                }
        
                public static void ConnectC(IPAddress ip, int port)
                {
                    IPEndPoint endPoint = new IPEndPoint(ip, port);
                    Console.WriteLine("Connecting...");
                    try
                    {
                        Klient.Connect(endPoint);
                        Console.WriteLine("Connected!");
                    }
                    catch
                    {
                        Console.WriteLine("Connection fail!");
                        return; 
                    }
                    Task t = new Task(WaitForMessages); 
                    t.Start(); 
                }
        
                public static void SendM()
                {
                    string message = "Actualy date is " + DateTime.Now; 
                    byte[] buffer = Encoding.UTF8.GetBytes(message);
                    Console.WriteLine("Sending: " + message);
                    Klient.Send(buffer);
                }
        
                public static void WaitForMessages()
                {
                    try
                    {
                        while (true)
                        {
                            byte[] buffer = new byte[64]; 
                            Console.WriteLine("Waiting for answer");
                            Klient.Receive(buffer, 0, buffer.Length, 0); 
        
                            string message = Encoding.UTF8.GetString(buffer); 
                            Console.WriteLine("Answer: " + message); 
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Disconnected");
                    }
                }
            }
        }
        

        【讨论】:

        • 请不要仅发布代码答案。你的回答应该包括解释它为什么起作用。
        • 另外,您应该在一个答案中同时包含客户端和服务器代码。不是两个。
        【解决方案6】:

        服务器:

        namespace SocketServer    
        {
            class Program
            {
                static Socket klient; 
                static void Main(string[] args)
                {
                    Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
                    IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8888); 
                    server.Bind(endPoint);
                    server.Listen(20);
                    while(true)
                    {
                        Console.WriteLine("Waiting...");
                        klient = server.Accept();
        
                        Console.WriteLine("Client connected");
                        Task t = new Task(ServisClient);
                        t.Start();
                    }
                }
        
                static void ServisClient()
                {
                    try
                    {
                        while (true)
                        {
                            byte[] buffer = new byte[64];
                            Console.WriteLine("Waiting for answer...");
                            klient.Receive(buffer, 0, buffer.Length, 0);
                            string message = Encoding.UTF8.GetString(buffer);
                            Console.WriteLine("Answer: " + message);
        
                            string answer = "Actualy date is " + DateTime.Now;
                            buffer = Encoding.UTF8.GetBytes(answer);
                            Console.WriteLine("Sending {0}", answer);
                            klient.Send(buffer);
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Disconnected");
                    }
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2021-12-04
          • 2023-04-03
          • 1970-01-01
          • 1970-01-01
          • 2012-12-14
          • 2010-10-26
          • 2019-07-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多