我有一个TCP侦听器应该从客户端收到一些消息但是当我启动这个简单的服务器时,我在server.Start()上收到类似的错误:
通常只允许使用每个套接字地址(协议/网络地址/端口)
这是我正在使用的代码:
public class ServerThread
{
private readonly int port = 8000;
private readonly IPAddress ip = IPAddress.Parse("xxxx");
/// <summary>
/// constructor, create the server thread
/// </summary>
public ServerThread()
{
Thread serverThread = new Thread(new ThreadStart(serverThreadStart));
serverThread.Start();
Console.WriteLine("Server thread started!");
}
/// <summary>
/// start the server
/// </summary>
private void serverThreadStart()
{
TcpListener server = null;
try
{
server = new TcpListener(ip, port);
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
Console.WriteLine("Waiting for client connection...");
TcpClient client = server.AcceptTcpClient();
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.ASCII.GetString(bytes, 0, i);
data = data.ToUpper();
Byte[] msg = Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
}
// Shutdown and end connection
client.Close();
}
}
catch(SocketException e)
{
Debug.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
}
主要方法只是这样做:
static void Main(string[] args)
{
new ServerThread();
}
答案 0 :(得分:1)
其他一些程序已经在TCP端口8000中列出。一次只有一个程序可以侦听TCP端口。您可以更改侦听器正在使用的TCP端口,也可以确定哪个程序还在侦听端口8000并停止它。
您可以通过从命令提示符运行netstat -a -b -p tcp
来找出端口上列出的程序。
答案 1 :(得分:1)