C# 기본 TCP 소켓 통신 예제 코드 (Basic socket communication in C#)
[출처 : http://blog.naver.com/mankeys?Redirect=Log&logNo=138953202 ]
1. TCP Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication_TCPEcho01
{
class TCP_Server
{
static void Main(string[] args)
{
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
Console.WriteLine("ipAddress"+ipAddress);
TcpListener tcp_Listener = new TcpListener(ipAddress, 5555);
tcp_Listener.Start();
while (true)
{
Console.WriteLine("1. EchoServer 대기상태.......");
TcpClient client = tcp_Listener.AcceptTcpClient(); //클라이언트와 접속
Console.WriteLine("2. Echo Client 접속....");
NetworkStream ns = client.GetStream();
StreamReader reader = new StreamReader(ns);
string msg = reader.ReadLine(); //메시지를 읽어 옴
Console.WriteLine("3. [클라이언트 메시지]:" + msg); //메시지 출력
StreamWriter writer = new StreamWriter(ns);
writer.WriteLine(msg); //네트워크 스트림에 쓰는 듯 함
writer.Flush();
Console.WriteLine("4. [Echo1]:" + msg);
writer.WriteLine(msg);
writer.Flush();
Console.WriteLine("5. [Echo2]:" + msg);
Console.WriteLine("6. 스트림과 TcpClient Close");
writer.Close();
reader.Close();
client.Close();
}
}
}
}
[출처] c# 소켓 통신 예제|작성자 겨울나무