属性 |
含义 |
Client |
获取或设置基础套接字 |
LingerState |
获取或设置套接字保持连接的时间 |
NoDelay |
获取或设置一个值,该值在发送或接收缓冲区未满时禁用延迟 |
ReceiveBufferSize |
获取或设置Tcp接收缓冲区的大小 |
ReceiveTimeout |
获取或设置套接字接收数据的超时时间 |
SendBufferSize |
获取或设置Tcp发送缓冲区的大小 |
SendTimeout |
获取或设置套接字发送数据的超时时间 |
方法 |
含义 |
Close |
释放TcpClient实例,而不关闭基础连接 |
Connect |
用指定的主机名和端口号将客户端连接到TCP主机 |
BeginConnect |
开始一个对远程主机连接的异步请求 |
EndConnect |
异步接受传入的连接尝试 |
GetStream |
获取能够发送和接收数据的NetworkStream对象 |
类 |
提供的方法 |
说明 |
TcpListener |
BeginAcceptTcpClient |
开始一个异步操作接受一个传入的连接尝试 |
|
EndAcceptTcpClient |
异步接受传入的连接尝试,并创建新的TcpClient处理远程主机通信 |
TcpClient |
BeginConnect |
开始一个对远程主机连接的异步请求 |
|
EndConnect |
异步接受传入的连接尝试 |
Socket |
BeginReceive |
开始从连接的Socket中异步接收数据 |
|
EndReceive |
结束挂起的异步读取 |
|
BeginSend |
将数据异步发送到连接的Socket |
|
EndSend |
结束挂起的异步发送 |
使用异步方式调用同步方法:
1.声明与要调用的方法具有相同签名的委托:
delegate void SendMessageDelegate(string message);
private void SendMessage(string message){
try{
bw.Write(message);
bw.Flush();
}catch{
MessageBox.Show("发送失败!");
}
}
2.通过轮询方法检查异步调用是否完成:
private bool needExit;
SendMessageDelegate d = new SendMessageDelegate(SendMessage);
IAsyncResult result = d.BeginInvoke(message,null,null);
while(result.IsCompleted == false)
{
if(needExit)
break;
Thread.Sleep(50);
}
3.使用EndInvoke结束异步调用:
private struct SendMessageStates{
public SendMessageDelegate d;
public IAsyncResult result;
}
private void AsyncSendMessage(string message)
{
SendMessageDelegate d = new SendMessageDelegate(SendMessage);
IAsyncResult result = d.BeginInvoke(message,null,null);
while(result.IsCompleted == false)
{
Thread.Sleep(50);
}
SendMessageStates states = new SendMessageStates();
states.d = d;
states.result = result;
Thread t = new Thread(FinishAsyncSendMessage);
t.IsBackground = true;
t.Start(states);
}
private void FinishAsyncSendMessage(object obj)
{
SendMessageStates states = (SendMessageStates)obj;
states.d.EndInvoke(states.result);
}
4.在异步调用中传递多个参数(参数可以使用out和ref关键字)
delegate void ReceiveMessageDelegate (out string receivemessage);
private void ReceiveMessage(out string receiveMessage){
receiveMessage = null;
try{
receiveMessage = br.ReadString();
}catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
SendMessageDelegate d = new SendMessageDelegate(ReceiveMessage);
IAsyncResult result = d.BeginInvoke( out receiveMessage ,null,null);
while(result.IsCompleted == false){
Thread.Sleep(250);
}
d.EndInvoke(out receiveString,result);