package com.test;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import org.java_websocket.WebSocket;
import org.java_websocket.server.WebSocketServer;
import org.java_websocket.framing.FrameBuilder;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
public class ChatServer extends WebSocketServer {
private final ArrayList<WebSocket> members = new ArrayList<WebSocket>();
private static ServerBox box;
public ChatServer( int port ) throws UnknownHostException {
super( new InetSocketAddress( InetAddress.getByName( "localhost" ), port ) );
}
public ChatServer( InetSocketAddress address ) {
super( address );
}
public ChatServer( String address ,int port) throws UnknownHostException {
super( new InetSocketAddress( InetAddress.getByName( address ), port ) );
}
@Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
members.remove(arg0);
}
@Override
public void onError(WebSocket arg0, Exception arg1) {
}
@Override
public void onMessage(WebSocket arg0, String arg1) {
//System.out.println("String message"+arg1);
if(members.size() == 1)
arg0.send("empty");
else
for(WebSocket ws : connections())
if(ws != arg0)
ws.send(arg1);
}
@Override
public void onMessage( WebSocket conn, ByteBuffer blob ) {
System.out.println("message");
for(WebSocket ws : connections())
if(ws!=conn)
{
ws.send(blob);
}
}
@Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
members.add(arg0);
if(members.size()>2){
members.remove(arg0);
arg0.send("warm");
}
}
public void onWebsocketMessageFragment( WebSocket conn, Framedata frame ) {
FrameBuilder builder = (FrameBuilder) frame;
builder.setTransferemasked( false );
conn.sendFrame( frame );
}
public static String getLocalHostIP(){
try{
InetAddress addr=InetAddress.getLocalHost();
return addr.getHostAddress();
}catch(Exception e){
return "localhost";
}
}
public static void main( String[] args ) throws UnknownHostException {
WebSocket.DEBUG = false;
int port = 8888;
try {
port = Integer.parseInt( args[ 0 ] );
} catch ( Exception ex ) {
}
ChatServer s = new ChatServer(getLocalHostIP(), port );
ChatServer.box = new ServerBox(s);
s.start();
System.out.println( "ChatServer IP: " + getLocalHostIP() );
box.displayArea.append("ChatServer IP: " + getLocalHostIP()+"\n");
System.out.println( "ChatServer started on port: " + s.getPort() );
box.displayArea.append("ChatServer started on port: " + s.getPort()+"\n");
}
}
- 1
- 2
前往页