2016-08-03 234 views
0

下面是套接字的代碼。套接字服務器未與JavaScript套接字客戶端連接

import java.io.*; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.net.SocketException; 
import java.util.Random; 

public class ChatSocketServer { 
    private ServerSocket severSocket = null; 
    private Socket socket = null; 
    private InputStream inStream = null; 
    private OutputStream outStream = null; 

    public ChatSocketServer() { 

    } 

    public void createSocket() { 
     try { 
      ServerSocket serverSocket = new ServerSocket(3339); 
      while (true) { 
       socket = serverSocket.accept(); 
       inStream = socket.getInputStream(); 
       outStream = socket.getOutputStream(); 
       System.out.println("Server Connected"); 
       createReadThread(); 
       createWriteThread(); 

      } 
     } catch (IOException io) { 
      io.printStackTrace(); 
     } 
    } 

    public void createReadThread() { 
     Thread readThread = new Thread() { 
      public void run() { 
       while (socket.isConnected()) { 
        try { 
         byte[] readBuffer = new byte[200]; 
         int num = inStream.read(readBuffer); 
         if (num > 0) { 
          byte[] arrayBytes = new byte[num]; 
          System.arraycopy(readBuffer, 0, arrayBytes, 0, num); 
          String recvedMessage = new String(arrayBytes, "UTF-8"); 
          System.out.println("server received :" + recvedMessage); 
         } else { 
          notify(); 
         } 
         ; 
         //System.arraycopy(); 

        } catch (SocketException se) { 
         System.exit(0); 

        } catch (IOException i) { 
         i.printStackTrace(); 
        } 

       } 
      } 
     }; 
     readThread.setPriority(Thread.MAX_PRIORITY); 
     readThread.start(); 
    } 

    public void createWriteThread() { 
     Thread writeThread = new Thread() { 
      public void run() { 

       while (socket.isConnected()) { 
        try { 
         while(true){ 
          synchronized (socket) { 
           Random random = new Random(); 
           int i = random.nextInt(100); 
           outStream.write(Integer.toString(i).getBytes("UTF-8")); 
           sleep(100); 
          } 
         }/* 
         BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in)); 
         sleep(100); 
         String typedMessage = inputReader.readLine(); 
         if (typedMessage != null && typedMessage.length() > 0) { 
          synchronized (socket) { 
           outStream.write(typedMessage.getBytes("UTF-8")); 
           sleep(100); 
          } 
         } else { 
notify(); 
} 
         ;*/ 
         //System.arraycopy(); 

        } catch (IOException i) { 
         i.printStackTrace(); 
        } catch (InterruptedException ie) { 
         ie.printStackTrace(); 
        } 

       } 
      } 
     }; 
     writeThread.setPriority(Thread.MAX_PRIORITY); 
     writeThread.start(); 

    } 

    public static void main(String[] args) { 
     System.out.println("char socket server got started"); 
     ChatSocketServer chatServer = new ChatSocketServer(); 
     chatServer.createSocket(); 

    } 
} 

上面的代碼工作正常,當我嘗試連接Java套接字客戶端。我不確定爲什麼在連接JavaScript時拋出錯誤。

的JavaScript

try{ 
    var host = "ws://localhost:3339/"; 
    var socket = new WebSocket(host); 
    console.log(socket.readyState); 
    socket.onopen = function(){ 
     console.log(socket.readyState); 
    }; 
     socket.onmessage = function(msg){ 
      console.log(msg.data); 
     }; 
     socket.onclose = function(){ 
      console.log(socket.readyState); 
     };   
     socket.onerror = function(error) { 
      // connection failed - try polling 
      console.log(socket.readyState); 
     }; 

    } catch(exception){ 
     console.log(exception); 
    } 

當我嘗試讀取從JavaScript值時,它引發以下錯誤:

WebSocket connection to 'ws://localhost:3339/' failed: Error during WebSocket handshake: Invalid status line

但我可以能夠通過使用Java代碼的服務器和客戶端之間同步上漲。

+1

一個WebSocket連接需要webSocket服務器,而不僅僅是一個普通的TCP服務器。有一個明確的webSocket協議必須被服務器支持。 – jfriend00

+0

websocket是一個通過http設計的特殊協議,通過增強http頭,你的服務器需要符合web socket協議 – Sanjeev

+0

@Sanjeev http://stackoverflow.com/questions/38752467/error-during-websocket-handshake-unexpected-response -code-404-時,試圖到C –

回答

1

webSocket連接需要特定的webSocket服務器,而不僅僅是普通的TCP服務器。當瀏覽器使用webSocket進行連接時,它具有特定的連接順序(從HTTP請求開始,然後升級到webSocket連接),它具有特定的安全方案,並且具有用於發送數據的特定數據格式。服務器必須支持所有這些才能正確接受來自瀏覽器的webSocket連接並與之通信。

關於invalid handshake的錯誤只是表明瀏覽器嘗試連接,但服務器沒有爲webSocket協議提供正確的響應。

由於它看起來像您的服務器在Java中,所以有很多用於Java的webSocket服務器實現。您應該可以抓住其中一個並使用它,而不是自己實現整個webSocket連接方案和協議。

你會發現這篇文章有幫助:

How to build Java WebSocket Applications Using the JSR 356 API

這裏對Java的答案(或許有點過時)關於其他的WebSocket庫:

WebSockets production ready server in Java?

相關問題