방금 C#에서 소켓 프로그래밍을 시작했습니다. 나는 간단한 클라이언트 - 서버 에코 애플리케이션을 개발하려고했다. 내가 만난 문제는 메시지를 클라이언트에 다시 표시하려고 할 때 수신하지 못하는 경우입니다. 나는 다양한 포럼에서 해결책을 찾기 위해 많은 시간을 보냈지 만 내 문제를 해결하는 데 도움이 될만한 것을 찾을 수 없었다.C# udp 클라이언트 - 서버 에코 프로그램
미리 감사드립니다. 앤드류 여기
코드입니다 :서버 :
static void Main(string[] args)
{
string data = "";
UdpClient server = new UdpClient(8008);
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine(" S E R V E R IS S T A R T E D ");
Console.WriteLine("* Waiting for Client...");
while (data != "q")
{
byte[] receivedBytes = server.Receive(ref remoteIPEndPoint);
data = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");
Console.WriteLine("Message Received " + data.TrimEnd());
server.Send(receivedBytes, receivedBytes.Length,remoteIPEndPoint);
Console.WriteLine("Message Echoed to" + remoteIPEndPoint + data);
}
Console.WriteLine("Press Enter Program Finished");
Console.ReadLine(); //delay end of program
server.Close(); //close the connection
}
}
클라이언트 :
static void Main(string[] args)
{
string data = "";
byte[] sendBytes = new Byte[1024];
byte[] rcvPacket = new Byte[1024];
UdpClient client = new UdpClient();
IPAddress address = IPAddress.Parse(IPAddress.Broadcast.ToString());
client.Connect(address, 8008);
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("Client is Started");
Console.WriteLine("Type your message");
while (data != "q")
{
data = Console.ReadLine();
sendBytes = Encoding.ASCII.GetBytes(DateTime.Now.ToString() + " " + data);
client.Send(sendBytes, sendBytes.GetLength(0));
rcvPacket = client.Receive(ref remoteIPEndPoint);
string rcvData = Encoding.ASCII.GetString(rcvPacket);
Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");
Console.WriteLine("Message Received: " + rcvPacket.ToString());
}
Console.WriteLine("Close Port Command Sent"); //user feedback
Console.ReadLine();
client.Close(); //close connection
}
2 대의 컴퓨터로 사용해 보셨습니까? – Guy
불행히도 컴퓨터가 1 대 밖에 없습니다. – user2226679
당신이 할 수 없다고 생각합니다. 2 대의 컴퓨터에서 프로그램을 시험해보십시오. – Guy