简单的实现tcp同步和异步,udp,串口通信
static List<TcpClientState> clientArray = new List<TcpClientState>();
static void AsyncTCP(IPEndPoint iep)
{
TcpListener listener = new TcpListener(iep);
listener.Start();
byte[] inValue = new byte[] { , , , , 0x20, 0x4e, , , 0xd0, 0x07, , };
listener.Server.IOControl(IOControlCode.KeepAliveValues, inValue, null);
#region//异步tcp
AsyncCallback dataReceiveAsyncCallback = null;
dataReceiveAsyncCallback = ar =>
{
TcpClientState innerclient = (TcpClientState)ar.AsyncState;
if ((innerclient.InnerClient == null) || (!innerclient.InnerClient.Connected))
return;
NetworkStream stream = innerclient.InnerClient.GetStream();
int num;
//异常断开
try { num = stream.EndRead(ar); }
catch { num = ; } if (num < )//断开连接
{
Console.WriteLine(innerclient.InnerClient.Client.RemoteEndPoint.ToString() + "断开连接");
clientArray.Remove(innerclient);
return;
} byte[] receivebytes = new byte[num];
Buffer.BlockCopy(innerclient.Buffer, , receivebytes, , num);
string s = Encoding.Default.GetString(receivebytes);
Console.WriteLine(s);
var data = Encoding.Default.GetBytes(string.Format("收到:{0}", s));
innerclient.InnerClient.GetStream().BeginWrite(data, , data.Length,
arw =>
{
((TcpClient)arw.AsyncState).GetStream().EndWrite(arw);
},innerclient.InnerClient);
stream.BeginRead(innerclient.Buffer, , innerclient.Buffer.Length, dataReceiveAsyncCallback, innerclient);
}; AsyncCallback connectAsyncCallbackcallback = null;
connectAsyncCallbackcallback = ar =>
{
var listen = (TcpListener)ar.AsyncState;
TcpClient client = listen.EndAcceptTcpClient(ar);
Console.WriteLine(client.Client.RemoteEndPoint.ToString() + "连接成功");
byte[] buf = new byte[client.ReceiveBufferSize];
TcpClientState innerclient = new TcpClientState(client, buf);
clientArray.Add(innerclient);
NetworkStream netstream = client.GetStream();
netstream.BeginRead(innerclient.Buffer, , innerclient.Buffer.Length, dataReceiveAsyncCallback, innerclient);
if (connectAsyncCallbackcallback == null) return;
listen.BeginAcceptTcpClient(connectAsyncCallbackcallback, ar.AsyncState);
};
listener.BeginAcceptTcpClient(connectAsyncCallbackcallback, listener);
Console.WriteLine("开始监听");
Console.Read(); #endregion
}
static void synctcp(IPEndPoint iep)
{
TcpListener listener = new TcpListener(iep);
Console.WriteLine("开始监听");
listener.Start();
byte[] inValue = new byte[] { , , , , 0x20, 0x4e, , , 0xd0, 0x07, , };
listener.Server.IOControl(IOControlCode.KeepAliveValues, inValue, null); #region //同步tcp
Thread listenThread = new Thread(() =>
{
while (true)
{
var client = listener.AcceptTcpClient();
Console.WriteLine(client.Client.RemoteEndPoint.ToString() + "连接成功");
Thread datareceiveThread = new Thread(() =>
{
NetworkStream stream = client.GetStream(); while (true)
{
if (stream.DataAvailable)
{
byte[] buf = new byte[client.Client.ReceiveBufferSize];
int len = client.Client.Receive(buf);
Console.WriteLine(Encoding.Default.GetString(buf, , len));
} }
});
datareceiveThread.Start();
}
});
listenThread.Start();
#endregion
}
static void udp(IPEndPoint iep)
{
Socket udpSocket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
udpSocket.Bind(iep);
var remotEndPoint = new IPEndPoint(IPAddress.Parse("10.6.179.44"), ); Thread thread=new Thread(() =>
{
while (true)
{
if (udpSocket.Available > )
{ byte[] buf = new byte[udpSocket.Available];
udpSocket.Receive(buf);
Console.WriteLine(Encoding.Default.GetString(buf));
udpSocket.SendTo(buf, remotEndPoint);
} }
});
thread.Start();
Console.WriteLine("wait");
Console.Read();
} static void com(string com, int port)
{
var m_port = new SerialPort(com, port); m_port.DataReceived += (obj, args) =>
{
int length = m_port.ReadBufferSize;
byte[] buf = new byte[length];
m_port.Read(buf, , length);
string s = Encoding.Default.GetString(buf);
Console.WriteLine(s);
m_port.Write(buf, , buf.Length); };
m_port.Open();
}
tcp异步客户端
/// <summary> 连接服务端
/// </summary>
/// <param name="ip">服务端IP</param>
/// <param name="port">服务端端口</param>
static void AsynConnect(string ip, int port)
{
var serverEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
var _client=new TcpClient();
_client.BeginConnect(serverEndPoint.Address, serverEndPoint.Port, asynresult =>
{
_client.EndConnect(asynresult);
Console.WriteLine("连上服务端{0}", _client.Connected);
if (_client.Connected)
{
NetworkStream stream = _client.GetStream();
byte[] buf = new byte[_client.ReceiveBufferSize];
AsyncCallback asyncCallback = null;
asyncCallback = asynreadresult =>
{
int num = ;
try
{
num = stream.EndRead(asynreadresult);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
num = ;
}
if (num == )
{
Console.WriteLine("服务端断开");
return;
}
byte[] receivebytes = new byte[num];
Buffer.BlockCopy(buf, , receivebytes, , num);
Console.WriteLine(Encoding.Default.GetString(receivebytes));
stream.BeginWrite(receivebytes, , receivebytes.Length, result =>
{
stream.EndRead(result);
}, null); stream.BeginRead(buf, , buf.Length, asyncCallback, null);
};
stream.BeginRead(buf, , buf.Length, asyncCallback, null);
} }, _client); Console.Read();
}