예, 클라이언트는 포트에만 연결할 수 있습니다. 그런 다음, 서버는이 클라이언트가 서버에 데이터를 보낼 수 있도록 클라이언트의 연결
예
클라이언트
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
서버에서 예입니다.
감사합니다,
난 당신이 클라이언트가 포트를 열 필요가 없습니다이 도움이 :)
알았어요. 하지만 클라이언트가 응답하지 않고 서버가 데이터를 전송해야한다면 어떻게 될까요? – Ace
의미 : 하나의 클라이언트가 "안녕 모두"를 입력하므로 서버가 thsi 메시지를 가져 와서 다른 모든 클라이언트에게 보냅니다. 그러나 한 클라이언트가 아무 것도 입력하지 않으면 응답을 기다리지 않습니다. 알고 계십니까? 내 말은 ? – Ace
@Ace 예. 서버는 클라이언트가 보낸 데이터가있는 경우에만 응답 할 수 있습니다. 또한 클라이언트가 연결된 후에 클라이언트에 응답 할 수있는 기회가 있습니다. –