WebSocket

服务器代码:

1、首先建立web服务器

2、导入包(地址:<a href="http://download.csdn.net/detail/qq_19984993/9541820">jar包地址</a>)

2、创建类

注意:@ServerEndpoint(value = "/websocket/chat")用于表示URL的访问地址

@ServerEndpoint(value = "/websocket/chat")
public class ChatAnnotation {

    private static final Logger log = Logger.getLogger(ChatAnnotation.class.getName());

    private static final String GUEST_PREFIX = "Guest";
    private static final AtomicInteger connectionIds = new AtomicInteger(0);
    private static final Set<ChatAnnotation> connections =
            new CopyOnWriteArraySet<ChatAnnotation>();

    private final String nickname;
    private Session session;

    public ChatAnnotation() {
        nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
    }


    @OnOpen
    public void start(Session session) {
        this.session = session;
        String message = String.format("* %s %s", nickname, "has joined.");
        broadcast(message);
        
        connections.add(this);
    }


    @OnClose
    public void end() {
        connections.remove(this);
        String message = String.format("* %s %s",
                nickname, "has disconnected.");
        broadcast(message);
    }


    @OnMessage
    public void incoming(String message) {
        // Never trust the client
        String filteredMessage = String.format("%s: %s",
                nickname, message.toString());
        broadcast(filteredMessage);
    }




    @OnError
    public void onError(Throwable t) throws Throwable {
        log.info("Chat Error: " + t.toString());
    }


    private static void broadcast(String msg) {
        for (ChatAnnotation client : connections) {
            try {
                synchronized (client) {
                    client.session.getBasicRemote().sendText(msg);
                }
            } catch (IOException e) {
                log.info("Chat Error: Failed to send message to client"+e.getMessage());
                connections.remove(client);
                try {
                    client.session.close();
                } catch (IOException e1) {
                    // Ignore
                }
                String message = String.format("* %s %s",
                        client.nickname, "has been disconnected.");
                broadcast(message);
            }
        }
    }
}

访问地址为:ws://localhost:8080/myWebSocket/websocket/chat

java客户端

java客户端使用的是java_websocket框架需要导入java_websocket.jar包(<a href="http://download.csdn.net/detail/qq_19984993/9541826">jar包地址</a>)

创建类:

public class MyClient extends WebSocketClient{

	public MyClient(URI serverUri, Draft draft) {
		super(serverUri, draft);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onMessage( String message ) {
//		send("hello");
		System.out.println("reciver"+message);
	}

	@Override
	public void onError( Exception ex ) {
		ex.printStackTrace();
	}

	@Override
	public void onOpen( ServerHandshake handshake ) {
		System.out.println("open");
		
	}

	@Override
	public void onClose( int code, String reason, boolean remote ) {
		send("I will go");
	}

测试:

String uri = "ws://localhost:8080/myWebSocket/websocket/chat";
MyClient client = new MyClient(URI.create(uri),new Draft_17());

try {
	ok = client.connectBlocking();
	client.close();
} catch (InterruptedException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值