C#——tcp通信


		
发送方:
        public static bool sendMessage(string message)
        {
            IPAddress remoteIP = IPAddress.Parse("127.0.0.1");//远程主机IP
            int remotePort = 61620;//远程主机端口

            byte[] sendData = Encoding.Default.GetBytes(message);//获取要发送的字节数组
            TcpClient client = new TcpClient();//实例化TcpClient
                try
                {
                    client.Connect(remoteIP, remotePort);//连接远程主机
                    NetworkStream stream = client.GetStream();//获取网络流
                    stream.Write(sendData, 0, sendData.Length);//将数据写入网络流
                    stream.Close();//关闭网络流
                    client.Close();//关闭客户端
                    return true;
                 }
                catch (System.Exception ex)
                {
                    Console.WriteLine("连接超时,服务器没有响应!");//连接失败
                    Console.ReadKey();
                    return false;
                }
     
        }

接收方:
public static void receiveMessage()
        {
            TcpClient client = null;
            NetworkStream stream = null;
            byte[] buffer = null;
            string receiveString = null;

            string hostName = Dns.GetHostName();   //获取本机名
            IPHostEntry localhost = Dns.GetHostByName(hostName);
            IPAddress localIP = localhost.AddressList[0];

            int localPort = 61620;
            TcpListener listener = new TcpListener(localIP, localPort);//用本地IP和端口实例化Listener
            listener.Start();//开始监听
       
           
            while(true)
            { 
                try
                {
                    client = listener.AcceptTcpClient();//接受一个Client
                    buffer = new byte[client.ReceiveBufferSize];
                    stream = client.GetStream();//获取网络流
                    stream.Read(buffer, 0, buffer.Length);//读取网络流中的数据
                    stream.Close();//关闭流
                    client.Close();//关闭Client
                    receiveString = Encoding.GetEncoding("UTF-8").GetString(buffer).Trim('\0');//转换成字符串
                    if (receiveString != null && receiveString.Trim() != "")
                    {
                        Console.WriteLine(receiveString);
                        pushMessage.push(receiveString);

                    }
                }
                catch(Exception e)
                {
                    logger.Error(e.Message);
                }


           }

        }	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值