c#实现本机Tcp通信

创建服务端

   private void StartServer()
        {
            try
            {
                // Set the TcpListener on port 13000.
                Int32 port = 8888;
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");

                // TcpListener server = new TcpListener(port);
                server = new TcpListener(localAddr, port);

                // Start listening for client requests.
                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[256];
                String data = null;

                // Enter the listening loop.
                while (true)
                {
                    Debug.Write("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also use server.AcceptSocket() here.
                    using TcpClient client = server.AcceptTcpClient();
                    Debug.WriteLine("Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.UTF8.GetString(bytes, 0, i);
                        Debug.WriteLine("Received: {0}", data);

                        Dispatcher.Invoke(() =>
                        {
                            ServerReceivedTextBox.Text = data;
                        });
                    }
                }
            }
            catch (SocketException ex)
            {
                Debug.WriteLine("SocketException: {0}", ex);
            }
            finally
            {
                server.Stop();
            }

        }


启动客户端

private void StartClient(object sender, RoutedEventArgs e)
{
    if (tcpClient == null)
    {
        tcpClient = new TcpClient();
        tcpClient.Connect(IPAddress.Loopback, 8888); //重要,用于本机测试
    }
}

通过客户端向服务端发送消息

    private void SendContent(object sender, RoutedEventArgs e)
    {
        byte[] msg = System.Text.Encoding.UTF8.GetBytes(sendingContents.Text);

        if (tcpClient != null && tcpClient.Connected)
        {
            var stream = tcpClient.GetStream();
            stream.Write(msg,0,msg.Length);
        }
    }
posted @   潜谷先生  阅读(504)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 三行代码完成国际化适配,妙~啊~
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
点击右上角即可分享
微信分享提示