服务器:
#region 服务器
int myPort = 7788;
TcpListener myListener = TcpListener.Create(myPort);
myListener.Start();
Task<TcpClient> acceptTcpClient = myListener.AcceptTcpClientAsync();
acceptTcpClient.ContinueWith((task) =>
{
NetworkStream networkStream = acceptTcpClient.Result.GetStream();
});
#endregion
客户端:
#region 客户端
TcpClient tcpClient = new TcpClient();
string serverIp = "192.168.10.11";
int serverPort = 7788;
IAsyncResult async = tcpClient.BeginConnect(IPAddress.Parse(serverIp), serverPort, null, null);
bool concentSuc = false;
concentSuc = async.AsyncWaitHandle.WaitOne(3000, false);
try
{
tcpClient.EndConnect(async);
}
catch (Exception e)
{
concentSuc = false;
}
if (concentSuc)
{
NetworkStream networkStream = tcpClient.GetStream();
}
else
{
tcpClient.Close();
tcpClient.Dispose();
}
#endregion
NetworkStream的简单使用:
继承自System.IO.Stream,读写都是那种循环读完的方式, 服务器/客户端通过对这个流的Read和Write来互相发数据。 Read就相当于接收,Write就相当于发送了。
NetworkStream下还有个DataAvailable属性,通过这个属性来判断有数据来了
个人笔记 仅供参考 欢迎指正 感谢观看
|