websocket 客户端连接

Websocket是应用层第七层上的一个应用层协议,它必须依赖 HTTP 协议进行一次握手 ,握手成功后,数据就直接从 TCP 通道传输,与 HTTP 无关了。轮训和长轮训由于http数据包的头部数据量往往很大(通常有400多个字节),但是真正被服务器需要的数据却很少,实时性较差,Websocket的数据传输是frame形式传输的,比如会将一条消息分为几个frame,按照先后顺序传输出去。

1、使用java代码实现websocket客户端连接到服务端

(1)引入 javax.websocket-client-api-1.1.jar、tyrus-standalone-client-1.9.jar 两个jar包

(2)代码编写

package mywebsocket;

import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.OnError;

@ClientEndpoint
public class WebsocketClient
{
	Session session = null;

	@OnOpen
	public void onOpen(Session session)
	{
		System.out.println("连接websocket成功执行");
		this.session = session;
	}


	@OnClose
	public void onClose(Session session, CloseReason reason)
	{
		System.out.println("关闭websocket执行");
		this.session = null;
	}


	@OnMessage
	public void onMessage(String message)
	{
		System.out.println("接收到服务端发送的信息");
		System.out.println("接收到的信息为:" + message);
	   try {
                session.getBasicRemote().sendText("客户端发送信息给服务端");
           } catch (IOException e) {
           
                e.printStackTrace();
           }
	}

        @OnError
        public void onError()
        {
                System.out.println("websocket连接发生异常执行");
        }
}
import java.net.URI;

import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

public class ConnectWebsocket {

	public static void main(String[] args)
	{
		boolean result = false;
		System.out.println("start connection ************************ ");
		
		String url = "ws://192.168.1.1:8080/connection/websocket";
		//如果为ssl协议,则请求中的ws改为wss
		//String url = "wss://192.168.1.1:8080/connection/websocket";
		
		try
		{
			WebSocketContainer container = ContainerProvider.getWebSocketContainer();

			Session session = container.connectToServer(WebsocketClient.class, new URI(url));
			session.getBasicRemote().sendText("发送信息给服务端");
			result = true;
		}
		
		catch (Exception e)
		{
			System.out.println("connect error and the message is " + e.getMessage());
		}
		
		System.out.println("connect result is " + result);
	
	}
	
}

 

2、使用JavaScript 实现websocket客户端的连接

 

(1)引入jquery

(2)js代码编写

$(function(){
	
	if (!window.WebSocket) {
		alert("浏览器不支持websocket");
		return false;
	}
	
	var socket = null;
        
        //调用关闭	

var url = "ws://192.168.1.1:8080/connection/websocket";//如果为ssl协议,则请求中的ws改为wss//var url = "wss://192.168.1.1:8080/connection/websocket";socket = new WebSocket(url); //建WebSocket对象socket.send("发送信息给服务端"); //调用该方法发送信息给服务端,另外可查看websocket状态: socket.readyStatesocket.onopen = function () {console.log("websocket建立连接时执行")};
        //调用关闭方法,socket.close();socket.onclose = function () {console.log("websocket关闭连接执行")};socket.onmessage = function (e) {var message = e.dataconsole.log("收到服务端的信息,信息为:" + message);socket.send("发送信息给服务端"); };socket.onerror = function () {console.log("websocket连接发生异常执行")}; })

 

你可能感兴趣的:(websocket 客户端连接)