我做了很多谷歌搜索,但我的问题没有太多运气。我是网络编程的新手并且正在努力学习,我试图建立一个简单的服务器&沟通的客户(遵循此处的在线教程 - > http://tech.pro/tutorial/704/csharp-tutorial-simple-threaded-tcp-server)
我遇到的问题是我一直得到异常“当尝试在服务器上启动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();
}
}
}
非常感谢任何帮助!
答案 0 :(得分:30)
ListenForClients
被调用两次(在两个不同的线程上) - 一次来自构造函数,一次来自Main
中的显式方法调用。当TcpListener
的两个实例尝试侦听同一端口时,您会收到该错误。
答案 1 :(得分:13)
您正在调试两次或更多次。所以应用程序可能一次运行更多。那么只会发生这个问题。您应该使用task-manager关闭所有调试应用程序,然后再次调试。
答案 2 :(得分:1)
我在Windows Server 2012 STD 64位上遇到了类似的问题,使用所有可用的Windows更新更新Windows后,我的问题得以解决。