3

我只想知道用一个套接字进行 2 路连接的正确方法是(C#)。

我需要客户端发送和接收来自服务器的数据,而无需打开客户端 PC / 路由器上的端口。

服务器将是一个多人游戏服务器,客户端不应额外打开端口来玩游戏。

那么一个简单的套接字连接是否以两种方式工作(服务器有一个套接字侦听器,客户端连接到服务器套接字)?

希望这段文字能很好地解释我的问题。

4

2 回答 2

6

是的,客户端只能连接到端口。然后,服务器可能会响应客户端的连接

客户端-服务器请求及其响应

例子

客户

IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);

  Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

  try
  {
     server.Connect(ip); //Connect to the server
  } catch (SocketException e){
     Console.WriteLine("Unable to connect to server.");
     return;
  }

  Console.WriteLine("Type 'exit' to exit.");
  while(true)
  {
     string input = Console.ReadLine();
     if (input == "exit")
        break;
     server.Send(Encoding.ASCII.GetBytes(input)); //Encode from user's input, send the data
     byte[] data = new byte[1024];
     int receivedDataLength = server.Receive(data); //Wait for the data
     string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength); //Decode the data received
     Console.WriteLine(stringData); //Write the data on the screen
  }

  server.Shutdown(SocketShutdown.Both);
  server.Close();

这将允许客户端向服务器发送数据。然后,等待服务器的响应。但是,如果服务器没有响应,客户端将挂起很长时间。

这是来自服务器的示例

IPEndPoint ip = new IPEndPoint(IPAddress.Any,9999); //Any IPAddress that connects to the server on any port
  Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); //Initialize a new Socket

  socket.Bind(ip); //Bind to the client's IP
  socket.Listen(10); //Listen for maximum 10 connections
  Console.WriteLine("Waiting for a client...");
  Socket client = socket.Accept();
  IPEndPoint clientep =(IPEndPoint)client.RemoteEndPoint;
  Console.WriteLine("Connected with {0} at port {1}",clientep.Address, clientep.Port);

  string welcome = "Welcome"; //This is the data we we'll respond with
  byte[] data = new byte[1024];
  data = Encoding.ASCII.GetBytes(welcome); //Encode the data
  client.Send(data, data.Length,SocketFlags.None); //Send the data to the client
  Console.WriteLine("Disconnected from {0}",clientep.Address);
  client.Close(); //Close Client
  socket.Close(); //Close socket

这将允许服务器在客户端连接时将响应发送回客户端。

谢谢,
我希望你觉得这有帮助:)

于 2012-10-29T13:04:33.150 回答
1

简单的套接字连接是全双工连接,即是的,使用单个套接字可以进行双向通信。

这是一个完整的例子

于 2012-10-29T12:29:59.983 回答