Programing

Websocket 서버 : 웹 소켓의 onopen 함수가 호출되지 않습니다.

lottogame 2020. 12. 2. 07:42
반응형

Websocket 서버 : 웹 소켓의 onopen 함수가 호출되지 않습니다.


C # 웹 소켓 서버를 구현하려고하는데 몇 가지 문제가 있습니다. 웹 서버 (ASP.NET)를 실행하여 자바 스크립트로 페이지를 호스팅하고 웹 소켓 서버는 C # 콘솔 애플리케이션으로 구현됩니다.

클라이언트 (JavaScript를 실행하는 크롬)에서 연결 시도를 감지하고 클라이언트에서 핸드 셰이크를 검색 할 수도 있습니다. 그러나 클라이언트는 내가 다시 보내는 핸드 셰이크를 받아들이지 않는 것 같습니다 ( onopen웹 소켓 함수는 절대 호출되지 않음).

나는 웹 소켓 프로토콜을 읽고 있는데 내가 뭘 잘못하고 있는지 알 수 없다. 다음은 서버 코드의 일부입니다.

Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8181);
listener.Bind(ep);
listener.Listen(100);
Console.WriteLine("Wainting for connection...");
Socket socketForClient = listener.Accept();
if (socketForClient.Connected)
{
    Console.WriteLine("Client connected");
    NetworkStream networkStream = new NetworkStream(socketForClient);
    System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
    System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream);

    //read handshake from client:
    Console.WriteLine("HANDSHAKING...");
    char[] shake = new char[255];
    streamReader.Read(shake, 0, 255);

    string handshake =
       "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" +
       "Upgrade: WebSocket\r\n" +
       "Connection: Upgrade\r\n" +
       "WebSocket-Origin: http://localhost:8080\r\n" +
       "WebSocket-Location: ws://localhost:8181\r\n" +
       "\r\n";

    streamWriter.Write(handshake);
    streamWriter.Flush();

내 로컬 호스트에서 포트 8080의 웹 서버와 포트 8181의 웹 소켓 서버로 실행 중입니다.

다른 인코딩 (ASCII, 바이트 및 16 진수)으로 핸드 셰이크를 보내려고 시도했지만 차이가없는 것 같습니다. 연결이 완전히 설정되지 않습니다. 자바 스크립트는 다음과 같습니다.

var ws;
var host = 'ws://localhost:8181';
debug("Connecting to " + host + " ...");
try {
 ws = new WebSocket(host);
} catch (err) {
 debug(err, 'error');
}
ws.onopen = function () {
 debug("connected...", 'success');
};
ws.onclose = function () {
 debug("Socket closed!", 'error');
};
ws.onmessage = function (evt) {
 debug('response: ' + evt, 'response');
};

크롬이 정보를 보내야 할 때 오류가 C # 서버에 있다고 생각하지만 말했듯이 onopen함수는 호출되지 않습니다.

간단히 말해서 제 질문 입니다. 여러분 중 누구라도이 작업을 수행 한 적이 있습니까? 그렇다면 어떻게 수행 했습니까? 그리고 원인 : 코드에 명백한 오류가 있습니까? (별로 묻지 않기를 바랍니다.)


아마도 인코딩 문제 일 것입니다. 내가 작성한 작동하는 C # 서버는 다음과 같습니다.

class Program
{
    static void Main(string[] args)
    {
        var listener = new TcpListener(IPAddress.Loopback, 8181);
        listener.Start();
        using (var client = listener.AcceptTcpClient())
        using (var stream = client.GetStream())
        using (var reader = new StreamReader(stream))
        using (var writer = new StreamWriter(stream))
        {
            writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
            writer.WriteLine("Upgrade: WebSocket");
            writer.WriteLine("Connection: Upgrade");
            writer.WriteLine("WebSocket-Origin: http://localhost:8080");
            writer.WriteLine("WebSocket-Location: ws://localhost:8181/websession");
            writer.WriteLine("");
        }
        listener.Stop();
    }
}

다음에서 호스팅되는 해당 클라이언트 localhost:8080:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <script type="text/javascript">
      var socket = new WebSocket('ws://localhost:8181/websession');
      socket.onopen = function() {
        alert('handshake successfully established. May send data now...');
      };
      socket.onclose = function() {
        alert('connection closed');
      };
    </script>
  </head>
  <body>
  </body>
</html>

This example only establishes the handshake. You will need to tweak the server in order to continue accepting data once the handshake has been established.


Please use UTF8 encoding to send text message.

There is an open source websocket server which is implemented by C#, you can use it directly.

http://superwebsocket.codeplex.com/

It's my open source project!


The .NET Framework 4.5 introduces support for WebSockets in Windows Communication Foundation. WebSockets is an efficient, standards-based technology that enables bidirectional communication over the standard HTTP ports 80 and 443. The use of the standard HTTP ports allow WebSockets to communicate across the web through intermediaries. Two new standard bindings have been added to support communication over a WebSocket transport. NetHttpBinding and NetHttpsBinding. WebSockets-specific settings can be configured on the HttpTransportBinding element by accessing the WebSocketSettings property.

I think it still uses SOAP though

http://msdn.microsoft.com/en-us/library/hh674271(v=vs.110).aspx

참고URL : https://stackoverflow.com/questions/2211898/websocket-server-onopen-function-on-the-web-socket-is-never-called

반응형