我已经做了很多谷歌搜索,但对我的问题没有太多运气。我是网络编程新手并试图学习,我尝试设置一个简单的服务器和客户端进行通信(遵循此处的在线教程 - > http://tech.pro/tutorial/704/csharp-tutorial -简单线程 TCP 服务器)
我遇到的问题是,当尝试在服务器上启动 TcpListener 时,我不断收到异常“通常只允许每个套接字地址(协议/网络地址/端口)使用一次”。
我尝试禁用防火墙,更改要使用的端口,移动变量但无济于事(客户端工作正常,但它显然无法找到服务器,因为我无法启动它)。
我见过描述如何使用 Socket.Poll() 的解决方案,但由于我只使用 TcpListener 对象,所以我不知道如何使用 Poll 函数。
我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;
namespace ServerTutorial {
class Server {
private readonly Thread m_listenThread;
public Server() {
m_listenThread = new Thread(new ThreadStart(ListenForClients));
m_listenThread.Start();
}
public void ListenForClients() {
var listener = new TcpListener(IPAddress.Any, 3000);
listener.Start();
while (true) {
//Blocks until a client has connected to the server
TcpClient client = listener.AcceptTcpClient();
//Send a message to the client
var encoder = new ASCIIEncoding();
NetworkStream clientStream = client.GetStream();
byte[] buffer = encoder.GetBytes("Hello Client!");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
//Create a thread to handle communication with the connected client
var clientThread = new Thread(new ParameterizedThreadStart(HandleClient));
clientThread.Start(client);
}
}
private void HandleClient(object clientObj) { //Param thread start can only accept object types, hence the cast
var client = (TcpClient) clientObj;
NetworkStream clientStream = client.GetStream();
var message = new byte[4096];
while (true) {
int bytesRead = 0;
try {
//Block until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
} catch {
//A socket error has occurred
System.Diagnostics.Debug.WriteLine("A socket error has occured");
break;
}
if (bytesRead == 0) {
//The client has disconnected from the server
System.Diagnostics.Debug.WriteLine("A client has disconnected from the server");
client.Close();
break;
}
//Message has been received
var encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
}
}
}
在我的主要方法中:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ServerTutorial {
class Program {
static void Main(string[] args) {
var server = new Server();
server.ListenForClients();
}
}
}
非常感谢任何帮助!
ListenForClients
被调用两次(在两个不同的线程上) - 一次来自构造函数,一次来自 Main
中的显式方法调用。当 TcpListener
的两个实例尝试侦听同一端口时,您会收到该错误。
您正在调试两次或多次。因此应用程序可能一次运行更多。那么只会出现这个问题。您应该使用任务管理器关闭所有调试应用程序,然后再次调试。
我在 Windows Server 2012 STD 64 位上遇到类似的问题,使用所有可用的 Windows 更新更新 Windows 后我的问题得到解决。
以管理员权限打开cmd
键入以下行:netstat -ano | findstr : 8080(写下你的端口)
你有这样的东西:
TCP 127.0.0.1:8080 0.0.0.0:0 监听 6932
现在终止此监听,输入: taskkill /F /PID 6932