多客户端服务器 - 2路连接的常用方法

时间:2012-10-29 12:21:00

标签: c# sql-server multithreading sockets client

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

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

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

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

希望文字能够解释我的问题。

2 个答案:

答案 0 :(得分:6)

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

Client-Server Request and its response

示例

客户端

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

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

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

答案 1 :(得分:1)

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

Here's a complete example