首页/C#语言/在C#中使用TcpClient与TcpListener发送与接收消息/

在C#中使用TcpClient与TcpListener发送与接收消息

2013-05-28
1712

本文介绍在C#中如何利用TcpClient与TcpListener进行简单的消息发送和接收。在使用时要注意,如果是本机发送与接收,发送消息时IP用127.0.0.1,如果是非本机接收,请在接收端打开相应的端口(本例中为13)。



using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

//接收方
public Form1(){
    InitializeComponent();

    Task.Factory.StartNew(() =>
    {
        TcpListener listener = null;
        TcpClient client = null;
        string message = string.Empty;

        while (true)  //循环接收消息,否则只能接收一次
        {
            try
            {
                listener = new TcpListener(IPAddress.Any, 13);
                listener.Start();

                client = listener.AcceptTcpClient();
                using (StreamReader sr = new StreamReader(client.GetStream()))
                {
                    message = sr.ReadToEnd();
                }
            }
            catch
            {
                message = "error";
            }
            finally
            {
                client.Close();
                listener.Stop();
            }

            MessageBox.Show(message);
        }
    });
}

//发送方
public void SendMessage(string receiverHostIP, int port, string message)
{
    TcpClient client = null;
    try
    {
        client = new TcpClient();
        client.Connect(receiverHostIP, port);

        using (NetworkStream ns = client.GetStream())
        {
            if (ns.CanWrite)
            {
                byte[] send = System.Text.Encoding.UTF8.GetBytes(message);  //如果不使用UTF8编码,则无法处理中文
                ns.Write(send, 0, send.Length);
            }
            else
            {
                //cannot send message
                MessageBox.Show("cannot send message");
                ns.Dispose();
            }
        }
    }
    catch
    {
    }
    finally
    {
        client.Close();
    }
}

private void button1_Click(object sender, EventArgs e)
{
    this.SendMessage("127.0.0.1", 13, "要发送的消息");
}
Copyright © 2021 技术探索 All Rights Reserved.