mobile Socket连接PC 的类

using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Net;
using  System.Threading;
using  System.Net.Sockets;
using  System.Windows.Forms;

namespace  MobileSocketCTL
{
    
//Client
    class MobileSocketClient : Control
    
{
        
private IPAddress hostIPAddress;
        
private IPEndPoint Server;
        
private Socket sock;
        
private const int BufferSize = 256;
        
private byte[] buffer = new byte[BufferSize];
        
private static ManualResetEvent connectDone = new ManualResetEvent(false);
        
private static ManualResetEvent sendDone = new ManualResetEvent(false);

        
public string ServerIP, ServerPort;
        
private string ShakeCode;

        
public delegate void RevdataEvent(int DataLength, string DataBuf);
        
public RevdataEvent ClientRevEvent;

        
public MobileSocketClient()
        
{
        }


        
public MobileSocketClient(string SIP, string SPort)
        
{
            ServerIP 
= SIP;
            ServerPort 
= SPort;
        }


        
public bool ClientConnectServer(String SendShakeCode)
        
{
            ShakeCode 
= SendShakeCode.Trim();
            
try
            
{
                hostIPAddress 
= IPAddress.Parse(ServerIP.Trim());
            }

            
catch
            
{
                
return false;
            }

            
try
            
{
                Server 
= new IPEndPoint(hostIPAddress, Int32.Parse(ServerPort));
                sock 
= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock.BeginConnect(Server, 
new AsyncCallback(ConnectCallBack), sock);
            }

            
catch (Exception ee)
            
{
                
return false;
            }

            
return true;
        }

        
private void ConnectCallBack(IAsyncResult ar)
        
{
            
try
            
{
                Socket client 
= (Socket)ar.AsyncState; //获取状态
                client.EndConnect(ar);
                
try
                
{
                    
byte[] byteData = Encoding.ASCII.GetBytes(ShakeCode);
                    sock.BeginSend(byteData, 
0, byteData.Length, 0new AsyncCallback(SendCallBack), sock);
                }

                
catch (Exception ee)
                
{
                }

                Thread thread 
= new Thread(new ThreadStart(ThreadProc));
                thread.Start();   
//开始接收数据线程
                connectDone.Set();  //将指定事件的状态设置为终止。
            }

            
catch
            
{
            }

        }


        
private void SendCallBack(IAsyncResult ar)
        
{
            
try
            
{
                Socket client 
= (Socket)ar.AsyncState;
                sendDone.Set();
            }

            
catch (Exception ee)
            
{
            }

        }


        
private void ThreadProc()
        
{
            
try
            
{
                sock.BeginReceive(buffer, 
0, BufferSize, 0new AsyncCallback(ReceiveCallBack), sock);
            }

            
catch (Exception ee)
            
{
            }

        }


        
private void ReceiveCallBack(IAsyncResult ar)
        
{
            
try
            
{
                Socket client 
= (Socket)ar.AsyncState;
                
int bytesRead = client.EndReceive(ar);//结束挂起的异步读取。返回接收到的字节数。
                StringBuilder sb = new StringBuilder();
                sb.Append(Encoding.ASCII.GetString(buffer, 
0, bytesRead));//储存数据
                string content = sb.ToString(); //转换为字符串
                if (ClientRevEvent != null)
                
{
                    
//RevdataEvent d = new RevdataEvent(ClientRevEvent);
                    this.Invoke(ClientRevEvent, new object[] { bytesRead, content });
                }

                sb.Remove(
0, content.Length);   //清除sb内容
                client.BeginReceive(buffer, 0, BufferSize, 0new AsyncCallback(ReceiveCallBack), client);
            }

            
catch (Exception ee)
            
{
            }

        }


        
public bool ClientSendText(string SendText)
        
{
            
try
            
{
                
string strSend = SendText.Trim();
                Byte[] ByteSend 
= Encoding.ASCII.GetBytes(strSend);
                
//sock.Send(ByteSend);
                sock.BeginSend(ByteSend, 0, ByteSend.Length, 0new AsyncCallback(SendCallBack), sock);
            }

            
catch
            
{
                
return false;
            }


            
return true;
        }


        
public bool ClientStopServer()
        
{
            
try
            
{
                sock.Close();
                ClientRevEvent 
= null;
            }

            
catch
            
{
                
return false;
            }

            
return true;
        }


        
~MobileSocketClient()
        
{
            ClientStopServer();
        }

    }


    
//Server
    class MobileSocketServer : Control
    
{
        
private IPAddress hostIPAddress;
        
private IPEndPoint Server;
        
private Socket listeningSocket;
        
private Socket handler;
        
private Socket mySocket;
        
private static ManualResetEvent Done = new ManualResetEvent(false);
        
private const int BufferSize = 256;
        
private byte[] buffer = new byte[BufferSize];
        
string  IP,port;
        
string SetupOK;
        
public delegate void RevdataEvent(int DataLength, string DataBuf);
        
public RevdataEvent ServerRevEvent;

        
public MobileSocketServer(string ServerIP, string ServerPort)
        
{
            IP 
= ServerIP;
            port 
= ServerPort;
        }


        
public bool SetupServer(string SetupOKStr)
        
{
            SetupOK 
= SetupOKStr;
            
try
            
{
                hostIPAddress 
= IPAddress.Parse(IP);
            }

            
catch {
                
return false;
            }

            
try
            
{  //通过组合服务的主机 IP 地址和端口号,IPEndPoint 类形成到服务的连接点。
                Server = new IPEndPoint(hostIPAddress, Int32.Parse(port));
                
// Create a socket object to establish a connection with the server
                listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                listeningSocket.Bind(Server); 
//绑定该主机端口
                listeningSocket.Listen(50); //监听端口,等待客户端连接请求。50是队列中最多可容纳的等待接受的传入连接数
                
//Accept 以同步方式从侦听套接字的连接请求队列中提取第一个挂起的连接请求,然后创建并返回新的 Socket。
                
//mySocket=listeningSocket.Accept();
                
//一个进程可以创建一个或多个线程以执行与该进程关联的部分程序代码。使用 ThreadStart 委托指定由线程执行的程序代码。
                Thread thread = new Thread(new ThreadStart(ThreadProc));
                thread.Start();
            }

            
catch (Exception ee) {
                
return false;
            }

            
return true;

        }

        
private void ThreadProc()
        
{
            
while (true)
            
{
                Done.Reset(); 
//将状态设为非终止
                listeningSocket.BeginAccept(new AsyncCallback(AcceptCallBack), listeningSocket);//开始一个异步操作来接受一个传入的连接尝试
                Done.WaitOne(); //阻塞当前线程,直到当前线程收到信号。
            }

        }


        
private void AcceptCallBack(IAsyncResult ar)//ar表示异步操作的状态。
        {
            Done.Set();
//设为终止
            mySocket = (Socket)ar.AsyncState; //获取状态
            handler = mySocket.EndAccept(ar);   //异步接受传入的连接尝试,并创建新的 Socket 来处理远程主机通信,获取结果
            try
            
{
                
byte[] byteData = Encoding.ASCII.GetBytes(SetupOK);
                
//调用SendCallBack异步发送数据,
                handler.BeginSend(byteData, 0, byteData.Length, 0new AsyncCallback(SendCallBack), handler);
            }

            
catch (Exception ee) {
            }


            Thread thread 
= new Thread(new ThreadStart(ThreadRev));
            thread.Start();
        }


        
private void SendCallBack(IAsyncResult ar)
        
{
            
try
            
{
                handler 
= (Socket)ar.AsyncState;  //获取状态
                int bytesSent = handler.EndSend(ar);//结束挂起的异步发送,返回向 Socket 发送的字节数
            }

            
catch { }
        }


        
private void ThreadRev()
        
{
            handler.BeginReceive(buffer, 
0, BufferSize, 0new AsyncCallback(ReadCallBack), handler);
        }


        
public void ReadCallBack(IAsyncResult ar)
        
{
            
try
            
{
                
int bytesRead = handler.EndReceive(ar); //结束挂起的异步读取,返回接收到的字节数。
                StringBuilder sb = new StringBuilder();   //接收数据的可变字符字符串,在通过追加、移除、替换或插入字符而创建它后可以对它进行修改。
                sb.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));//追加字符串
                string content = sb.ToString();   //转换为字符串
                sb.Remove(0, content.Length);   //清除sb内容
                if (ServerRevEvent != nullthis.Invoke(ServerRevEvent, new object[] { bytesRead, content });
                handler.BeginReceive(buffer, 
0, BufferSize, 0new AsyncCallback(ReadCallBack), handler);
            }

            
catch
            
{

            }

        }


        
public bool ServerSendText(string SendData)
        
{
            
try
            
{
                Byte[] ByteSend 
= Encoding.ASCII.GetBytes(SendData);
                handler.BeginSend(ByteSend, 
0, ByteSend.Length, 0new AsyncCallback(SendCallBack), handler);
            }

            
catch {
                
return false;

            }

            
return true;
        }


        
public bool ServerStopServer()
        
{
            
try
            
{
                listeningSocket.Close();
                ServerRevEvent 
= null;
            }

            
catch
            
{
                
return false;
            }

            
return true;
        }


        
~MobileSocketServer()
        
{
            ServerStopServer();
        }

    }

}

你可能感兴趣的:(socket)