웹 개발/네트워크
[C#] TCP/IP 소켓 프로그래밍_ echo 프로그램
배세
2023. 7. 20. 15:41
- 클라이언트가 메시지를 보내면 서버가 클라이언트에게 재전송 하는 프로그램
- 서버
public static void CreateEchoServer()
{
using (Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.30.1"), 20000);
serverSocket.Bind(endPoint);
serverSocket.Listen(20);
using (Socket clientSocket = serverSocket.Accept()) {
Console.WriteLine(clientSocket.RemoteEndPoint);
while (true) {
byte[] buffer = new byte[1024];
// 클라이언트에서 전송한 데이터를 받는다.
int totalBytes = clientSocket.Receive(buffer);
//반환값이 없으면 클라이언트가 연결을 종료했다고 판단
if (totalBytes < 1) {
Console.WriteLine("클라이언트 연결 종료");
return;
}
//받은 데이터 역직렬화
string str = Encoding.UTF8.GetString(buffer);
Console.WriteLine("받은 메시지: " + str);
//클라이언트에게 받은 메시지를 재전송
clientSocket.Send(buffer);
}
}
}
}
- 클라이언트
public static class EchoClient
{
public static void CreateEchoClient() {
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.30.1"), 20000);
socket.Connect(endPoint);
while (true) {
//클라이언트에서 입력받은 메시지를 서버로 전송
string str = Console.ReadLine();
// exit 라는 메시지를 받으면 프로그램 종료
if (str == "exit") {
return;
}
// 메시지를 바이트 배열로 직렬화
byte[] buffer = Encoding.UTF8.GetBytes(str);
//서버에 데이터 전송
socket.Send(buffer);
byte[] buffer2 = new byte[1024];
int bytesRead = socket.Receive(buffer2);
//1바이트 미만을 받으면 서버가 접속종료한 것으로 판단
if (bytesRead < 1) {
Console.WriteLine("서버 연결 종료");
}
string str2 = Encoding.UTF8.GetString(buffer2);
Console.WriteLine("보낸 메시지: " + str2);
}
}
}
- 결과