2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > 捷作服务器 修改套接字端口 如何解决错误“每个套接字地址(协议/网络地址/端口)通

捷作服务器 修改套接字端口 如何解决错误“每个套接字地址(协议/网络地址/端口)通

时间:2018-11-24 08:19:10

相关推荐

捷作服务器 修改套接字端口 如何解决错误“每个套接字地址(协议/网络地址/端口)通

我遇到的问题是,我保持获取异常“尝试启动服务器上的TcpListener时,通常只允许每个套接字地址(协议/网络地址/端口)的一个用法。

我试过禁用我的防火墙,更改要使用的端口,移动变量但无济于事(客户端正常工作,但显然无法找到服务器,因为我无法启动它)。

我见过描述使用Socket.Poll()的解决方案,但由于我只使用TcpListener对象,我不知道如何使用Poll函数。

我的代码:

using System;

using System.Collections.Generic;

using System.Linq;

using .Sockets;

using ;

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

注意''mingw-w64'你需要'closesocket()'而不是'close()'来释放端口。 –

捷作服务器 修改套接字端口 如何解决错误“每个套接字地址(协议/网络地址/端口)通常只允许使用一次”?...

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。