블로그 이미지
따시쿵

calendar

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

Notice

2015. 3. 12. 16:41 C# with TCP/IP

프로그램 설명


한 프로그램에서 여러개의 포트를 열어서 작업이 필요한 경우입니다.

포트별로 쓰레드를 만들어서 작업하는 방식입니다. 예제에서는 8080, 8081 포트를 엽니다.




실행 후



프로그램 작성 순서


1. ListenPorts.cs


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
class ListenPorts
{
    Socket[] socket;
    IPEndPoint[] ipEndPoint;
 
    internal ListenPorts(IPEndPoint[] ipEndPoint)
    {
        this.ipEndPoint = ipEndPoint;
        socket = new Socket[ipEndPoint.Length];
    }
 
    public void beginListen()
    {
        for(int i = 0; i < ipEndPoint.Length; i++)
        {
            socket[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket[i].Bind(ipEndPoint[i]);
 
            Thread t_handler = new Thread(threadListen);
            t_handler.IsBackground = true;
            t_handler.Start(socket[i]);
        }
    }
 
    private void threadListen(object sender)
    {
        Socket m_client = sender as Socket;
        byte[] data = new byte[1024];
         
        try
        {
            m_client.Listen(100);
            Socket newSocket = m_client.Accept();
            int bytes = newSocket.Receive(data);
 
            IPEndPoint remoteIP = newSocket.RemoteEndPoint as IPEndPoint;
            IPEndPoint localIP = newSocket.LocalEndPoint as IPEndPoint;
 
            Console.WriteLine("server ip : {0} remote ip : {1} ", localIP.ToString(), remoteIP.ToString());
            Console.WriteLine("Received data : {0}", Encoding.Unicode.GetString(data, 0, bytes));
             
            string msg = "Welcome to multiple server";
            byte[] buffer = Encoding.Unicode.GetBytes(msg);
            newSocket.Send(buffer, buffer.Length, SocketFlags.None);
            Console.WriteLine("Send data : {0}", msg);
            Console.WriteLine();
        }
        catch(SocketException se)
        {
            Console.WriteLine(se.Message);
        }
         
    }
}


2. 서버 프로그램


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Program
{
    static void Main(string[] args)
    {
        IPEndPoint ipEndPoint1 = new IPEndPoint(IPAddress.Any, 8080);
        IPEndPoint ipEndPoint2 = new IPEndPoint(IPAddress.Any, 8081);
 
        IPEndPoint[] ipEndPoint = new IPEndPoint[2] { ipEndPoint1, ipEndPoint2 };
        //IPEndPoint[] ipEndPoint = new IPEndPoint[1] { ipEndPoint1 };
 
        ListenPorts listenport = new ListenPorts(ipEndPoint);
        listenport.beginListen();
        Console.WriteLine("Begin Listen");
        Console.WriteLine();
         
        Console.ReadKey();
    }
}


3. 클라이언트 프로그램


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
65
66
67
68
69
70
71
class Program
{
    static void Main(string[] args)
    {
        byte[] data = new byte[1024];
 
        //TCP Client
 
        Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName());
        Console.WriteLine();
 
        //Set the IP address of the server, and its port.
        IPEndPoint ipep1 = new IPEndPoint(IPAddress.Parse("192.168.0.12"), 8080);
        IPEndPoint ipep2 = new IPEndPoint(IPAddress.Parse("192.168.0.12"), 8081);
        string welcome = "Hello, Multiple server ! ";
 
        // port 8080 으로 전송
        try
        {
            // 소켓 생성
            Socket server1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
            // 메시지 전송
            data = Encoding.Unicode.GetBytes(welcome);
            server1.Connect(ipep1);
            server1.Send(data);
            Console.WriteLine("Send by the port : {0}", server1.LocalEndPoint.ToString());
            Console.WriteLine("Send data : {0}", welcome);
 
            // 메시지 받음
            byte[] msg = new byte[1024];
            int bytes = server1.Receive(msg);
            Console.WriteLine("Received data : {0}", Encoding.Unicode.GetString(msg, 0, bytes));
            Console.WriteLine();
            // 소켓 닫기
            server1.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
 
        // port 8081 으로 전송
        try
        {
            // 소켓 생성
            Socket server2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
            // 메시지 전송
            data = Encoding.Unicode.GetBytes(welcome);
            server2.Connect(ipep2);
            server2.Send(data);
            Console.WriteLine("Send by the port : {0}", server2.LocalEndPoint.ToString());
            Console.WriteLine("Send data : {0}", welcome);
 
            // 메시지 받음
            byte[] msg = new byte[1024];
            int bytes = server2.Receive(msg);
            Console.WriteLine("Received data : {0}", Encoding.Unicode.GetString(msg, 0, bytes));
            Console.WriteLine();
            // 소켓 닫기
            server2.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
 
        Console.ReadKey();
    }
}


posted by 따시쿵