TcpClient连续发送数据以后报错:通常每个套接字地址(协议/网络地址/端口)只允许使用一次
客户端连续不断的用TcpClient往服务器发送数据,服务器端开了一个线程去监听端口并且接收处理数据。
但是在发送了3800次左右以后,发送数据的地方报错:通常每个套接字地址(协议/网络地址/端口)只允许使用一次。
主要代码如下:
客户端:
服务器端:
但是在发送了3800次左右以后,发送数据的地方报错:通常每个套接字地址(协议/网络地址/端口)只允许使用一次。
主要代码如下:
客户端:
public void Post(byte[] b)
{
TcpClient client = null;
NetworkStream ns = null;
try
{
client = new TcpClient();
client.Connect(Ip, Port); //这个方法被调用了3800次左右以后,这里报错:通常每个套接字地址(协议/网络地址/端口)只允许使用一次。
client.ReceiveTimeout = 300000;
ns = client.GetStream();
//发送至服务器端
ns.Write(b, 0, b.Length);
ns.Flush();
}
catch (Exception e)
{
}
finally
{
if (ns != null)
{
ns.Close();
ns.Dispose();
}
if (client != null)
{
client.Close();
}
}
}服务器端:
public class ServerClient
{
private TcpListener tcpListener = null;
//下面这个线程用来监听端口,在服务器开启以后就启动下面的线程
private Thread threadTcp = null;
threadTcp = new Thread(new ThreadStart(tcpServerProcess));
threadTcp.Start();
private void tcpServerProcess()
{
try
{
tcpListener = new TcpListener(IPAddress.Any, Port);
tcpListener.Start();
while (true)
{
try
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(new WaitCallback(ReciveTcp), tcpClient);
}
catch
{
}
}
}
catch
{
}
}
private void ReciveTcp(object state)
{
TcpClient client = state as TcpClient;
NetworkStream ns = null;
try
{
client.ReceiveTimeout = 300000;
ns = client.GetStream();
byte[] bytes = new byte[client.ReceiveBufferSize];
ns.Read(bytes, 0, (int)client.ReceiveBufferSize);
//处理数据
}
catch
{
}
finally
{
if (ns != null)
{
ns.Close();
ns.Dispose();
}
if (client != null)
{
client.Close();
}
}
}
}
...全文
相关推荐
c#向指定端口发送数据,监听指定端口
c#向指定端口发送数据,监听指定端口,使用端口监听获取数据信息,向指定端口发送需要的数据
FrmTcpServer TcpClient.rar
Tcp通信协议;winform制作Demo; 语言C#;内含客户端与服务端代码 纯属开源代码
TCPServer/TCPClient 通讯实例
实现了TCPServer,TCPClient 组件之间的通讯,有需要的可以在此基础上继续增加新的功能
Tcpclient和Tcpserver实现简单通讯.rar
利用Tcpclient和Tcpserver实现简单通讯,分两个程序,一个为客户端(发送),一个为服务端(接收)。代码功能只提供最简单的发送和接收,简单易懂
TcpListener 和TcpClient使用总结
TcpListener类以同步阻塞方式提供于监听和接收外来连接请求的方法。 TcpClient类实现了使用发送和接收数据的套接字。 在c# .NET中,远程连接被表示为流,所以可以用流处理方式读取和写入而进行通信。



