웹소켓은 이름 그대로 웹버전의 TCP 또는 소켓이라고 생각하면된다.

웹소켓은 서버와 클라이언트 간에 socket connection을 유지해서 언제든 양방향 통신 또는 데이터 전송이 가능하다.

(참고자료 : HTTP통신 vs Socket통신 - http://k9e4h.tistory.com/150)


여기서는 웹소켓을 편하게 사용하기 위해 websocket-sharp를 사용할 것이다.

https://github.com/sta/websocket-sharp


우선 websocket-sharp.dll 파일을 받아 프로젝트에 참조추가해준다.

websocket-sharp.dll



1. 서버

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
using WebSocketSharp;
using WebSocketSharp.Server;
 
namespace websocket
{
    public partial class MainWindow : Window
    {
        private static MainWindow g_Main = null;
        public static MainWindow getWindow
        {
            get
            {
                return g_Main;
            }
        }
 
        public void addText(string text)
        {
            this.Dispatcher.Invoke((Action)(() =>
            {
                string myText = Console.Text;
                myText += text;
                Console.Text = myText;
            }));
        }
 
        public MainWindow()
        {
            InitializeComponent();
            g_Main = this;
        }
        private WebSocketServer webSocketServer = null;
 
        private void Start_Click(object sender, RoutedEventArgs e)
        {
            if (webSocketServer != null)
                return;
 
            Int32 port = 4649;
            webSocketServer = new WebSocketServer(port);
            webSocketServer.AddWebSocketService<Echo>("/Echo");
            webSocketServer.AddWebSocketService<Chat>("/Chat");
            webSocketServer.Start();
            Console.Text += "서버시작\n";
        }
 
        private void Stop_Click(object sender, RoutedEventArgs e)
        {
            if (webSocketServer != null)
                webSocketServer.Stop();
 
            webSocketServer = null;
            Console.Text += "서버종료\n";
        }
    }
}
cs


우선 참조한 websocket-sharp를 쓰기위해 using해준다. 서버는 .Server까지 넣어준다.

1
2
using WebSocketSharp;
using WebSocketSharp.Server;
cs


그리고 웹소켓서버를 만들어준다.

1
private WebSocketServer webSocketServer = null;
cs


시작버튼을 누르면 서버를 설정하고 Start시킨다.

1
2
3
4
5
6
Int32 port = 4649;
webSocketServer = new WebSocketServer(port);
webSocketServer.AddWebSocketService<Echo>("/Echo");
webSocketServer.AddWebSocketService<Chat>("/Chat");
webSocketServer.Start();
Console.Text += "서버시작\n";
cs

포트번호는 아무번호나 사용해도되지만 이미 정해진 포트번호나 다른곳에서 사용하는 포트와 중복되면 안된다.

새로운 웹소켓서버를 생성하고 서비스를 추가하고 시작한다.


종료버튼을 누르면 웹소켓서버의 Stop을 불러준다.

1
webSocketServer.Stop();
cs



Chat 서버

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Threading.Tasks;
using WebSocketSharp;
using WebSocketSharp.Server;
 
namespace websocket
{
    public class Chat : WebSocketBehavior
    {
        protected override void OnMessage(MessageEventArgs e)
        {
            var text = e.Data;
            text += "\n";
            MainWindow.getWindow.addText(text);
 
            Sessions.Broadcast(e.Data);
        }
    }
}
 
cs

class는 WebSocketBehavior를 상속해준다.

Chat서버가 메세지를 수신하면 OnMessage 함수가 호출된다.


함수가 호출되면 받은 메세지를 textbox에 출력하고 

Sessions.Broadcast를 통해 받은 메세지 그대로 세션에 연결된 클라이언트들에게 메세지를 보낸다.

Posted by misty_
,