我已经做了很多谷歌搜索,但对我的问题没有太多运气。我是网络编程的新手并正在尝试学习,我试图设置一个简单的服务器和客户端进行通信(遵循位于此处的在线教程-> 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();
}
}
}
非常感谢任何帮助!