はい、クライアントはポートにのみ接続できます。その後、サーバーはクライアントの接続に応答する場合があります
例
クライアント
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
これにより、サーバーはクライアントの接続時にクライアントに応答を返すことができます。
ありがとう、
これがお役に立てば幸いです:)