C# 4.0 “每个套接字地址(协议/网络地址/端口)通常只允许使用一次”
我正在尝试用一个简单的客户端和一个服务器进行一些网络编程。当我的客户机连接到服务器时,服务器打印消息通常只允许使用每个套接字地址协议/网络地址/端口一次 我使用的端口是6000,localhost是主机 我正在使用Tcp客户端C# 4.0 “每个套接字地址(协议/网络地址/端口)通常只允许使用一次”,c#-4.0,websocket,C# 4.0,Websocket,我正在尝试用一个简单的客户端和一个服务器进行一些网络编程。当我的客户机连接到服务器时,服务器打印消息通常只允许使用每个套接字地址协议/网络地址/端口一次 我使用的端口是6000,localhost是主机 我正在使用Tcp客户端 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Soc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
namespace ConsoleTankClientVersion1
{
class Program
{
static void Main(string[] args)
{
TcpClient client = null;
NetworkStream netStream = null;
//server ip
String server = "127.0.0.1";
//server port
int servPort = 6000;
//The input string is converted to a stream of bytes
byte[] byteBuffer = Encoding.ASCII.GetBytes("JOIN#");
try
{
// Create socket that is connected to server on port 6000
client = new TcpClient(server, servPort);
Console.WriteLine("Connected to server... sending join string");
netStream = client.GetStream();
// Send the encoded string to the server
netStream.Write(byteBuffer, 0, byteBuffer.Length);
Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
int totalBytesRcvd = 0; // Total bytes received so far
int bytesRcvd = 0; // Bytes received in last read
// Receive the same string back from the server
while (totalBytesRcvd < byteBuffer.Length)
{
if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd,
byteBuffer.Length - totalBytesRcvd)) == 0)
{
Console.WriteLine("Connection closed prematurely.");
break;
}
totalBytesRcvd += bytesRcvd;
}
Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,
Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
TcpTimedWait延迟为30秒
最大用户端口值为60000如果您的代码有问题,您可以提出问题并添加您拥有的相关代码吗?@honk KK现在我编辑了我的帖子,以便包含代码。感谢您看到的错误只有在多个套接字尝试绑定到同一本地IP/端口时才会发生。此代码中没有显式绑定,因此客户端将使用操作系统专门选择的随机IP/端口来避免此类错误。此客户端代码获取错误的唯一方法是如果所有可能的端口都已在使用中,这称为端口耗尽。不过,您说您尚未显示的服务器代码正在报告错误。服务器应绑定到单个端口,并接受该端口上的所有客户端。因此,服务器获得错误的唯一方法是,在任何客户端连接到某个IP/端口之前,服务器尝试侦听已在使用的IP/端口。它会在成功打开端口后报告错误,除非您正在打开更多端口以响应客户端活动,而您不应该这样做,除非您的协议需要其他端口,例如FTP。由于您尚未显示服务器代码,因此很难诊断您的问题。