一个基本的实现是这样的:
public class ChatServer extends WebSocketServer
{
private final String TAG = LogHelper.makeLogTag(ChatServer.class);
private Map<String, WebSocket> clients = new ConcurrentHashMap<>();
public ChatServer(int port)
{
super(new InetSocketAddress(port));
}
public ChatServer(InetSocketAddress address)
{
super(address);
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
String uniqueID = UUID.randomUUID().toString();
clients.put(uniqueID, conn);
conn.send(WrapHelper.regToJson(uniqueID));
conn.send(WrapHelper.resToJson("Welcome to the server!"));
broadcast((WrapHelper.resToJson("new connection: " + handshake.getResourceDescriptor()))); //This method sends a message to all clients connected
LogHelper.e(TAG, conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!");
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
broadcast(WrapHelper.resToJson(conn + " has left the room!"));
LogHelper.e(TAG, conn + " has left the room!");
}
@Override
public void onMessage(WebSocket conn, String message) {
Gson gson = new Gson();
final Frame frame = gson.fromJson(message, Frame.class);
if (frame != null) {
LogHelper.e(TAG, "frame: " + frame);
switch (frame.getCmd()) {
case CMD_MSG:
broadcast(message);
break;
case CMD_REG_USER:
break;
}
}
LogHelper.e(TAG, conn + ": " + message);
}
@Override
public void onMessage(WebSocket conn, ByteBuffer message) {
broadcast(message.array());
LogHelper.e(TAG, conn + ": " + message);
}
@Override
public void onError(WebSocket conn, Exception ex)
{
ex.printStackTrace();
if (conn != null) {
// some errors like port binding failed may not be assignable to a specific websocket
}
}
@Override
public void onStart()
{
LogHelper.e(TAG, "Server started!");
setConnectionLostTimeout(0);
setConnectionLostTimeout(100);
}
}
在此示例中,您可以看到我们正在覆盖WebSocketServer
类的抽象方法。您可以创建一个界面来更新您的 UI。
然后在您的主要活动中,您可以像这样使用它:
@Override
protected void onCreate(Bundle savedInstanceState)
{
...
ChatServer server = new ChatServer(DEFAULT_CHAT_PORT);
server.start();
...
}
我在这里有一个完整的聊天示例。