기본카테고리

[C#] TCP/IP 소켓통신 서버 & 클라이언트 예제

DevReff 2014. 2. 19. 10:38




728x90

서버소스.
접속한 클라이언트에게 메세지를 10번 보낸다.
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
    using System.Net.Sockets;
    using System.Threading;
 
    private TcpListener client;
 
    public ServerForm()
    {
        InitializeComponent();
    }
 
    private void ServerForm_Load(object sender, EventArgs e)
    {
        // 클라이언트의 접속요청을 받는 스레드 시작
        Thread thr = new Thread(new ThreadStart(ListenerThread));
        thr.Start();
    }
 
    public void ListenerThread()
    {
        client = new TcpListener(12345);
        client.Start();
 
        while (true)
        {
            // 클라이언트의 연결 요청 확인
            while (!client.Pending())
            {
                Thread.Sleep(100);
            }
 
            // 클라이언트와의 통신처리 스레드 시작
            ConnectionHandler newConnection = new ConnectionHandler();
            newConnection.threadListener = this.client;
            Thread newThread = new Thread(new ThreadStart(newConnection.clientHandler));
            newThread.Start();
        }
    }
}
 
public class ConnectionHandler
{
    public TcpListener threadListener;
 
    public void clientHandler()
    {
        TcpClient client = threadListener.AcceptTcpClient();
        NetworkStream ns = client.GetStream();
 
        string msg = "Welcome to server\n";
 
        byte[] send = Encoding.ASCII.GetBytes(msg);
 
        for (int i = 0; i < 10; i++)
        {
            ns.Write(send, 0, send.Length);
            Thread.Sleep(1000);
        }
    }
}


클라이언트 소스.
서버에서 수신한 데이터를 리치 텍스트박스에 출력한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System.Net.Sockets;
using System.Threading;
 
public partial class Form1 : Form
{
    private TcpClient server;
    private NetworkStream ns;
    private bool isRunning = true;
 
    public Form1()
    {
        InitializeComponent();
    }
 
    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            server = new TcpClient("127.0.0.1", 12345);
            ns = server.GetStream();
            Thread recvThread = new Thread(new ThreadStart(RecvThread));
            recvThread.Start();
        }
        catch (SocketException)
        {
            MessageBox.Show("서버와의 연결에 실패했습니다.");
        }
    }
 
    delegate void LogToForm(string msg);
    private void Log(string msg)
    {
        serverMessage.AppendText(msg);
        serverMessage.ScrollToCaret();
    }
 
    public void RecvThread()
    {
        byte[] buffer = new byte[1024];
        string msg;
 
        while (isRunning)
        {
            try
            {
                ns.Read(buffer, 0, buffer.Length);
                msg = Encoding.ASCII.GetString(buffer);
                serverMessage.Invoke(new LogToForm(Log), new object[] { msg });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
 
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        isRunning = false;
 
        ns.Close();
        server.Close();
    }
}