8,757
社区成员
发帖
与我相关
我的任务
分享
public void start()
{
syn = SynchronizationContext.Current;
if (string.IsNullOrEmpty(ipaddress) || string.IsNullOrWhiteSpace(ipaddress))
{
MessageBox.Show("通讯IP地址不能为空");
return;
}
IPAddress ip = IPAddress.Parse(ipaddress);
IPEndPoint ipe = new IPEndPoint(ip, sPort);
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
socketEventArg = new SocketAsyncEventArgs()
{
RemoteEndPoint = new IPEndPoint(ip, sPort)
};
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(socketEventArg_Completed);
clientSocket.ConnectAsync(socketEventArg);
if (timer == null)
timer = new Timer(new TimerCallback(StartReceive), null, 2000, 2000);
}
int sInterval = 0;
public void StartReceive(object o)
{
try
{
if (clientSocket.Connected == true)
{
socketEventArg.SetBuffer(byteReceive, 0, byteReceive.Length);
clientSocket.ReceiveAsync(socketEventArg);
}
else
{
sInterval = sInterval + 1;
if (sInterval == 3)
{
sInterval = 0;
clientSocket.ConnectAsync(socketEventArg);
}
}
}
catch
{ }
}
int sReadtime = 0;
void socketEventArg_Completed(object sender, SocketAsyncEventArgs e)
{
switch (e.LastOperation)
{
case SocketAsyncOperation.Connect:
if (e.SocketError !=SocketError.Success)
{
clientSocket.ConnectAsync(socketEventArg);
return;
}
e.SetBuffer(byteReceive, 0, byteReceive.Length);
clientSocket.ReceiveAsync(e);
break;
case SocketAsyncOperation.Receive:
string strText = System.Text.Encoding.UTF8.GetString(e.Buffer, 0, e.Buffer.Length);
if (string.IsNullOrEmpty(strText))
{
//clientSocket.Close();
}
else
{
DogMsg.SendTwoMsg("end");
if (string.IsNullOrEmpty(strText))
return;
if (strText.IndexOf("\0") > 0)
{
strText = strText.Substring(1, strText.IndexOf("\0") - 1);
}
syn.Post(DoThing, strText);
}
break;
case SocketAsyncOperation.None:
isSend = false;
break;
}
}