GPRS的環境下用mobile Socket串連PC的類

來源:互聯網
上載者:User

代碼如下:

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, 0, new 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, 0, new 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, 0, new 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, 0, new 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, 0, new 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, 0, new 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 != null) this.Invoke(ServerRevEvent, new object[] ...{ bytesRead, content });
handler.BeginReceive(buffer, 0, BufferSize, 0, new AsyncCallback(ReadCallBack), handler);
}
catch
{

}
}

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

}
return true;
}

public bool ServerStopServer()
{
try
{
listeningSocket.Close();
ServerRevEvent = null;
}
catch
{
return false;
}
return true;
}

~MobileSocketServer()
{
ServerStopServer();
}
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.