双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

TcpClient连续发送数据以后报错:通常每个套接字地址(协议/网络地址/端口)只允许使用一次

fihuang fihuang 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
客户端连续不断的用TcpClient往服务器发送数据,服务器端开了一个线程去监听端口并且接收处理数据。
但是在发送了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();
}
}
}
}
...全文
评论 13
收藏 已收藏
分享
返回顶部
fihuang
C# 111,129 成员 642,540 内容