// Create an instance of the Server and waits for a connexion
net.createServer(function(sock) {
// Receives a connection - a socket object is associated to the connection automatically
console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
// Add a 'data' - "event handler" in this socket instance
sock.on('data', function(data) {
//data was received in the socket and converting it into string
var textChunk = data.toString('utf8');
io.emit('message', textChunk); //socket.io is supposed to send the data to the browser
console.log(textChunk);
});
// Add a 'close' - "event handler" in this socket instance
sock.on('close', function(data) {
// closed connection
console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
});
}).listen(PORT, HOST);
答案 0 :(得分:1)
您可以使用github.com/TooTallNate/Java-WebSocket将Java端(WebSocketServer)连接到Javascript端(浏览器)。
Java方面:
final class Gateway extends WebSocketServer {
private WebSocket _webSocket;
Gateway( IDataManager dataManager, IConfiguration config) {
super( new InetSocketAddress( <host>, <port> );
new Thread( this ).start();
}
@Override
public void onOpen( WebSocket conn, ClientHandshake handshake ) {
final String request = handshake.getResourceDescriptor();
final String[] req = request.split( "[/=]" );
System.out.printf( "request: %s\n", Arrays.toString( req ));
_webSocket = conn;
...
}
public void publish( ... ) {
final ByteBuffer buffer = ByteBuffer.allocate( ... );
buffer.order( ByteOrder.BIG_ENDIAN );
buffer.putXXX( ... );
buffer.flip();
_webSocket.send( buffer );
}
@Override
public void onMessage( WebSocket conn, String buffer ) {
System.out.printf( "%s\n", buffer );
}
@Override
public void onMessage( WebSocket conn, ByteBuffer buffer ) {
try {
System.out.printf( "%d bytes received from %s",
buffer.remaining(), conn.getRemoteSocketAddress());
if( buffer.position() == buffer.limit()) {
buffer.flip();
}
buffer.order( ByteOrder.BIG_ENDIAN );
final byte xxx = buffer.getXxx();
...
}
catch( final Throwable t ) {
t.printStackTrace();
}
}
@Override
public void onError( WebSocket conn, Exception ex ) {
ex.printStackTrace();
}
@Override
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
System.out.printf( "code: %d, reason: %s, remote: %s\n", code, reason, remote ? "true" : "false" );
}
}
Javascript方面:
var webSocket = new WebSocket(
'ws://' + smoc.PROTOCOL_HOST +
':' + smoc.PROTOCOL_PORT +
'/viewID=' + $scope.viewID );
$scope.webSocket.binaryType = "arraybuffer";
$scope.webSocket.onmessage = function( evt ) {
...
};