Socket(这样写可以实现P2P通信)

C# code
       protected override void Dispose( bool disposing )
       {
           try 
            {
               serverSocket.Close();//释放资源             
               mythread.Abort ( ) ;//中止线程 
            } 
            catch{ } 
           if( disposing )
           {
               if (components != null) 
               {
                   components.Dispose();
               }
           }
           base.Dispose( disposing );
       }


C# code
        Thread mythread ;
        Socket serverSocket;
        private void BeginListen()
        {           
            //侦听服务器的所有网络IP和指定端口
            IPEndPoint remotePoint=new IPEndPoint(IPAddress.Any,int.Parse(txtPort.Text));
 
            serverSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);                    
 
            serverSocket.Bind(remotePoint);
            serverSocket.Listen(10);
 
            this.label1.Text="正在监听...";
  
            //这个死循环让监听持续进行
            while(true)
            {
                try
                {
                    Socket newSocket=serverSocket.Accept();
                    //得到远程机(发送信息到服务器的机器)的端口
                    IPEndPoint clientep=(IPEndPoint)newSocket.RemoteEndPoint;   
                     
                    //得到发送端的IP                   
                    this.txtLocalIP.Text="远端IP:"+clientep.Address.ToString()+"; 端口:"+clientep.Port.ToString();
 
                    string rmsg="";                   
 
                    int bytes=0;
                    //这个循环让Socket.Receive()方法持续进行
                    while(true)
                    {
                        byte[] byteMessage=new byte[10];
                        //循环执行,它会从头到尾自动接收数据给存放对象。
                        //Receive的返回值是一个接收数据的字节数,必须得到该值,用以控制循环的次数和转换成字符串的字符数。                       
                        bytes=newSocket.Receive(byteMessage);
 
                        //控制循环次数
                        if(bytes<=0)
                            break;
 
                        //用Encoding.GetEncoding("gb2312"); 来写的话字符“@”就显示不正常
                        System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                                                                         
                        string msg=encoding.GetString(byteMessage,0,bytes);
                        rmsg=rmsg+msg;
                    }
                                                             
                    string sTime = DateTime.Now.ToShortTimeString();
                    //得到远程机(发送信息到服务器的机器)的端口
                    rmsg=sTime+":"+"Message from:"+newSocket.RemoteEndPoint.ToString()+"\r\n"+rmsg+"\r\n"+"\r\n";
                     
                    this.txtMessage.Text=this.txtMessage.Text+rmsg;                   
 
                }
                catch(SocketException ex)
                {
                    this.label1.Text+=ex.ToString();
                }
            }
        }
 
        private void BeginSend()
        {             
            string ip=this.txtIP.Text;
            string port=this.txtPort.Text;
            IPAddress serverIp=IPAddress.Parse(ip);            
            int serverPort=Convert.ToInt32(port);
 
            //远程端口
            IPEndPoint iep=new IPEndPoint(serverIp,serverPort);  
            byte[] byteMessage;
             
            Socket socketSend=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);           
            try
            {
                if(socketSend.Connected==false)
                {
                    //联接到远程端
                    socketSend.Connect(iep); 
                }
 
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                byteMessage=new byte[encoding.GetByteCount(textSendMessage.Text)];
                byteMessage=encoding.GetBytes(textSendMessage.Text);
 
                socketSend.Send(byteMessage);           
                socketSend.Shutdown(SocketShutdown.Both);
                socketSend.Close();
                textSendMessage.Text="";
            }
            catch(Exception ex)
            {MessageBox.Show(ex.ToString());}
        }
 
        private void btnBeginSend_Click(object sender, System.EventArgs e)
        {
            BeginSend();
        }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值