精华内容
下载资源
问答
  • java实现websocket客户端与服务端的连接
  • websocket 客户端与服务端数据传输 [removed] socket = new WebSocket('ws://127.0.0.1:8900','chat'); console.log(socket) socket.onopen = function(){ console.log('connected success'); socket.send('...
  • WebSocket客户端服务端实例源码 WebSocket ws实例 HTML5 用java实现的服务端 Websocket服务器的正常通信 可以用客户端测试任意语言的服务端,也可以用服务端测试任意语言的客户端 众所周知,Web 应用的交互过程...
  • 1.依赖 <dependency> <groupId>org.java-websocket</groupId> <artifactId>Java-WebSocket<...客户端 @Slf4j @Component public class SocketClient { @Bean public Web

    依赖

    客户端:

    <dependency>
    	<groupId>org.java-websocket</groupId>
    	<artifactId>Java-WebSocket</artifactId>
    	<version>1.3.8<version>
    </dependency>
    

    服务端:

    <dependency>
    	<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    

    客户端

    @Slf4j
    @Component
    public class SocketClient {
    	
    	@Bean
    	public WebSocketClient webSocketClient(){
    		try{
    			WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:8090/test-one"),new Draft_6455()){
    			@Override
    			public void onOpen(ServerHandshake handshakedata){
    				log.info("[websocket]连接成功");
    				//webSocketClient.send需在onOpen回调之后,即于客户端建立连接之后
    				//测试代码
    				ThreadPoolManager.getInstance().execute(new Task(this));
    			}
    
    			@Override
    			public void onMessage(String message){
    				log.info("accept message success is {}",message);
    				//执行接收到消息体后的相应操作
    			}
    		
    			@Override
    			public void onClose(int code,String reason,boolean remote){
    				log.info("[websocket]退出连接")
    			}
    			
    			@Override
    			public void onError(Exception ex){
    				log.info("[websocket]连接错误",ex);
    			
    			}
    		};
    		webSocketClient.connect();
    		return webSocketClient;
    	} catch(Exception e){
    		e.printStackTrace();
    	}
    	return null;
    	}
    
    	class Task implements Runnable{
    		public WebSocketClient webSocketClient;
    		Task(WebSocketClient webSocketClient){
    			this.webSocketClient = webSocketClient;
    		}
    	}
    		@SneakeyThrows @Override
    		public void run(){
    			while(true){
    				webSocketClient.send("client test message");
    				Thread.sleep(1000);
    			}
    		}
    }
    

    服务端(to One)

    @ServerEndpoint("/test-one")
    @Component
    @Slf4j
    public class OneToOneServer{
    	/**
    	* 用于存放所有在线客户端
    	*/
    	private static Map<String,Session> clients = new ConcurrentHashMap<>();
    
    	@OnOpen
    	public void onOpen(Session session){
    		log.info("有新的客户端上线,客户端id:{}",session.getId());
    		//解决数据字节过多,客户端连接中断,默认8190;
    		//字节过多也可采用分片
    		session.setMaxTextMessageBufferSize(81900);
    		clients.put(session.getId(),session);
    	}
    	
    	@OnClose
    	public void onClose(Session session){
    		String clientId = session.getId();
    		log.info("有客户端离线,客户端Id:{}",clientId);
    		clients.remove(clientId);
    	}
    	
    	@OnError
    	public void onError(Session session,Throwable throwable){
    		String clientId = session.getId();
    		if(clients.get(clientId) != null){
    			log.info("发生了错误,移除客户端:{}",clientId);
    			clients.remove(clientId);
    		}
    		throwable.printStackTrace();
    	}
    
    	@OnMessage
    	public void onMessage(String message,Session session){
    		log.info("收到客户端{}发来的消息",message);
    		String test = "server test message";
    		sendTo(session.getId(),test);
    	}
    
    	/**
    	* 发送消息
    	* @param clientId
    	*/
    	private void sendTo(String clientId,String message){
    		Session session = clients.get(clientId);
    		if(session != null){
    			try{
    				session.getBasicRemote().sendText(message);
    			} catch(IOException e){
    				e.printStackTrace();
    			}
    		}
    	}
    }
    

    客户端重连(定时任务)

    @Component
    @Slf4j
    public class WebSocketHearBeat{
    
    	//重连简单实现
    	
    	@Autowired
    	private WebSocketClient webSocketClient;
    
    	@Scheduled(cron = "5/2 * * * * ?")
    	public void heartBeat(){
    		try{
    			webSocketClient.sendPing();
    		} catch(Exception e){
    			log.info("断开连接 开始重试");
    			webSocketClient.reconnect();
    			//1.3.5的包没有这个方法
    		}
    	}
    }
    
    展开全文
  • 基于C#net4.5websocket客户端与服务端

    万次阅读 2018-05-18 17:13:52
    视频流采用websocket传输。所以研究了一下C#的websocket。 首先使用HttpListener进行侦听,HttpListener监听需要启动管理员权限才能运行,或者注册该端口,注册如下: 已管理员身份运行cmd.exe 输入下面两个命令 ...

    只支持win8以上系统以及windows server2012以上系统

    最近在研究视频传输给浏览器,然后使用H5标签解码。视频流采用websocket传输。所以研究了一下C#的websocket。

    首先使用HttpListener进行侦听,HttpListener监听需要启动管理员权限才能运行,或者注册该端口,注册如下:

    已管理员身份运行cmd.exe 输入下面两个命令
    netsh http delete urlacl url=http://127.0.0.1:8080/

    netsh http add urlacl url=http://*:9999/ user=Everyone listen=yes

    查看已经加载的url  :netsh http show urlacl

     

    *******************websocket服务端****************************************

    第一步:创建HttpListener类,并启动监听:

                var listener = new HttpListener();
                listener.Prefixes.Add("http://10.10.13.140:8080/");
                listener.Start();

    第二步:等待连接

    var context = listener.GetContext();

    第三步:接收websocket

                    var wsContext = await context.AcceptWebSocketAsync(null);
                    var ws = wsContext.WebSocket;
                    Console.WriteLine("WebSocket connect");

    第四步:开始异步接收数据

                        //接收数据
                        var wsdata = await ws.ReceiveAsync(abuf, cancel);
                        Console.WriteLine(wsdata.Count);
                        byte[] bRec = new byte[wsdata.Count];
                        Array.Copy(buf, bRec, wsdata.Count);
                        Console.WriteLine(Encoding.Default.GetString(bRec));

    第五步:释放资源

                    //注意,使用完,记得释放,不然会有内存泄漏
                    ws.Dispose();

    *******************websocket客户端****************************************

    这里使用ClientWebSocket类进行

    第一步:创建ClientWebSocket

    ClientWebSocket webSocket = new ClientWebSocket();

    第二步:建立websocket连接

                    await webSocket.ConnectAsync(new Uri("ws://10.10.13.140:8080/"), cancellation);
                    Console.WriteLine(111);

    第三步:发送数据

                    //发送数据
                    await webSocket.SendAsync(new ArraySegment<byte>(bsend), WebSocketMessageType.Binary, true, cancellation);
    
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "1", cancellation);

    第四步:释放资源

                    //释放资源
                    webSocket.Dispose();

     

     

     

    为了方便大家学习,整理了一下服务端和客户端的代码,采用C# net4.5 vs2017开发环境

    连接如下:

    点击打开链接

    *************--------------备注---------------******************************************

     

    发现win7下无法运行,参考

    https://msdn.microsoft.com/en-us/library/system.net.websockets.clientwebsocket(v=vs.110).aspx

    关键部分如下:

    Some of the classes and class elements in the System.Net.WebSockets namespace are supported on Windows 7, Windows Vista SP2, and Windows Server 2008. However, the only public implementations of client and server WebSockets are supported on Windows 8 and Windows Server 2012. The class elements in the System.Net.WebSockets namespace that are supported on Windows 7, Windows Vista SP2, and Windows Server 2008 are abstract class elements. This allows an application developer to inherit and extend these abstract class classes and class elements with an actual implementation of client WebSockets.

     

     

     

     

    展开全文
  • 用JAVA实现WebSocket客户端与服务端

    千次阅读 2019-08-25 10:26:07
    服务端: 1、添加Jar包依赖: <dependency>  <groupId>javax.websocket</groupId>  <artifactId>javax.websocket-api</artifactId>  <version>1.1</version>  <...

    服务端:

     1、添加Jar包依赖:

    <dependency>
      <groupId>javax.websocket</groupId>
      <artifactId>javax.websocket-api</artifactId>
      <version>1.1</version>
      <scope>provided</scope>
    </dependency>

     2、创建一个WebSocket服务端类MyWebSocketServer,并在类前添加@ServerEndpoint(value = "/websocket")注解,@ServerEndpoint(value = "/websocket")注释端点表示将 WebSocket 服务端运行在 ws://[Server 端 IP 或域名]:[Server 端口]/项目名/websocket 的访问端点

     3、实现onOpen、onClose、onMessage、onError等方法

      

    实例代码:

    MyWebSocketServer 类

    import java.io.IOException;
    import javax.websocket.EncodeException;
    import javax.websocket.OnClose;
    import javax.websocket.OnError;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    import org.apache.commons.lang.StringUtils;
    import org.apache.log4j.Logger;
    import net.sf.json.JSONObject;
    
    @ServerEndpoint(value = "/websocket")
    public class MyWebSocketServer {
    
      private Logger logger = Logger.getLogger(MyWebSocketServer.class);
      private Session session;
    
      /**
       * 连接建立后触发的方法
       */
      @OnOpen
      public void onOpen(Session session){
        this.session = session;
        logger.info("onOpen"+session.getId());
        WebSocketMapUtil.put(session.getId(),this);
      }
    
    
      /**
       * 连接关闭后触发的方法
       */
      @OnClose
      public void onClose(){
        //从map中删除
        WebSocketMapUtil.remove(session.getId());
        logger.info("====== onClose:"+session.getId()+" ======");
      }
    
    
      /**
       * 接收到客户端消息时触发的方法
       */
      @OnMessage
      public void onMessage(String params,Session session) throws Exception{
        //获取服务端到客户端的通道
        MyWebSocketServer myWebSocket = WebSocketMapUtil.get(session.getId());
        logger.info("收到来自"+session.getId()+"的消息"+params);
        String result = "收到来自"+session.getId()+"的消息"+params;
        //返回消息给Web Socket客户端(浏览器)
        myWebSocket.sendMessage(1,”成功!”,result);
      }
    
    
      /**
       * 发生错误时触发的方法
       */
      @OnError
      public void onError(Session session,Throwable error){
        logger.info(session.getId()+"连接发生错误"+error.getMessage());
        error.printStackTrace();
      }
    
      public void sendMessage(int status,String message,Object datas) throws IOException{
        JSONObject result = new JSONObject();
        result.put("status", status);
        result.put("message", message);
        result.put("datas", datas);
            this.session.getBasicRemote().sendText(result.toString());
        }
    
    }


    WebSocketMapUtil 工具类

    import java.util.Collection;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.ConcurrentMap;
    
    public class WebSocketMapUtil {
    
      public static ConcurrentMap<String, MyWebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    
      public static void put(String key, MyWebSocketServer myWebSocketServer){
           webSocketMap.put(key, myWebSocketServer);
        }
    
        public static MyWebSocketServer get(String key){
             return webSocketMap.get(key);
        }
    
        public static void remove(String key){
             webSocketMap.remove(key);
        }
     
        public static Collection<MyWebSocketServer> getValues(){
            return webSocketMap.values();
        }
    }

     

     客户端:

     1、添加Jar包依赖:

    <dependency>
      <groupId>org.java-websocket</groupId>
      <artifactId>Java-WebSocket</artifactId>
      <version>1.3.8</version>
    </dependency>

     2、创建Web Socket客户端类MyWebSocketClient,并继承WebSocketClient

     3、实现构造器,重写onOpen、onClose、onMessage、onError等方法

       

    实例代码:

    MyWebSocketClient 类

    import java.net.URI;
    import org.activiti.engine.impl.util.json.JSONObject;
    import org.apache.log4j.Logger;
    import org.java_websocket.client.WebSocketClient;
    import org.java_websocket.handshake.ServerHandshake;
    
    public class MyWebSocketClient extends WebSocketClient{
    
      Logger logger = Logger.getLogger(MyWebSocketClient.class);
     
      public MyWebSocketClient(URI serverUri) {
         super(serverUri);
      }
    
      @Override
      public void onOpen(ServerHandshake arg0) {
        // TODO Auto-generated method stub
        logger.info("------ MyWebSocket onOpen ------");
      }
    
      @Override
      public void onClose(int arg0, String arg1, boolean arg2) {
         // TODO Auto-generated method stub
         logger.info("------ MyWebSocket onClose ------");
      }
    
      @Override
      public void onError(Exception arg0) {
         // TODO Auto-generated method stub
         logger.info("------ MyWebSocket onError ------");
      }
    
      @Override
      public void onMessage(String arg0) {
         // TODO Auto-generated method stub
         logger.info("-------- 接收到服务端数据: " + arg0 + "--------");
      }
    }

     

    MyTest 测试类

    public class MyTest{
    
      public static void main(String[] arg0){
        MyWebSocketClient myClient = new MyWebSocketClient("此处为websocket服务端URI");
        // 往websocket服务端发送数据
        myClient.send("此为要发送的数据内容");
      }
    
    }

    WebSocketConfig.java

    package com.ruoyi.web.websocket;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    
    /**
     * 开启WebSocket支持
     * @author zhengkai
     */
    @Configuration  
    public class WebSocketConfig {  
    	
        @Bean  
        public ServerEndpointExporter serverEndpointExporter() {  
            return new ServerEndpointExporter();  
        }  
      
    } 
    
    

     

    展开全文
  • 最近公司在搞一个项目刚好需要用到WebSocket技术来实现实时数据的传输,因为之前也没接触过,所以捣鼓了好些天,最近恰巧有空就写写。有误的地方还请大牛们能及时指正。 项目背景:基于spring+spring MVC+mybatis...

    最近公司在搞一个项目刚好需要用到WebSocket技术来实现实时数据的传输,因为之前也没接触过,所以捣鼓了好些天,最近恰巧有空就写写。有误的地方还请大牛们能及时指正。

    项目背景:基于spring+spring MVC+mybatis框架的maven项目

     

    服务端:

     1、添加Jar包依赖:

    <dependency>
      <groupId>javax.websocket</groupId>
      <artifactId>javax.websocket-api</artifactId>
      <version>1.1</version>
      <scope>provided</scope>
    </dependency>

     2、创建一个WebSocket服务端类MyWebSocketServer,并在类前添加@ServerEndpoint(value = "/websocket")注解,@ServerEndpoint(value = "/websocket")注释端点表示将 WebSocket 服务端运行在 ws://[Server IP 或域名]:[Server 端口]/项目名/websocket 的访问端点

     3、实现onOpenonCloseonMessageonError等方法

      

    实例代码:

    MyWebSocketServer 类

    import java.io.IOException;
    import javax.websocket.EncodeException;
    import javax.websocket.OnClose;
    import javax.websocket.OnError;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    import org.apache.commons.lang.StringUtils;
    import org.apache.log4j.Logger;
    import net.sf.json.JSONObject;
    
    @ServerEndpoint(value = "/websocket")
    public class MyWebSocketServer {
      
    private Logger logger = Logger.getLogger(MyWebSocketServer.class);   private Session session;   /**   * 连接建立后触发的方法    */   @OnOpen   public void onOpen(Session session){     this.session = session;     logger.info("onOpen"+session.getId());     WebSocketMapUtil.put(session.getId(),this);   }
      
    /**   * 连接关闭后触发的方法   */   @OnClose   public void onClose(){     //从map中删除     WebSocketMapUtil.remove(session.getId());     logger.info("====== onClose:"+session.getId()+" ======");   }
      
    /**    * 接收到客户端消息时触发的方法    */   @OnMessage   public void onMessage(String params,Session session) throws Exception{     //获取服务端到客户端的通道     MyWebSocketServer myWebSocket = WebSocketMapUtil.get(session.getId());     logger.info("收到来自"+session.getId()+"的消息"+params);     String result = "收到来自"+session.getId()+"的消息"+params;     //返回消息给Web Socket客户端(浏览器)     myWebSocket.sendMessage(1,”成功!”,result);   }

      
    /**    * 发生错误时触发的方法   */   @OnError   public void onError(Session session,Throwable error){     logger.info(session.getId()+"连接发生错误"+error.getMessage());     error.printStackTrace();   }   public void sendMessage(int status,String message,Object datas) throws IOException{     JSONObject result = new JSONObject();     result.put("status", status);     result.put("message", message);     result.put("datas", datas); this.session.getBasicRemote().sendText(result.toString()); } }


    WebSocketMapUtil 工具类

    import java.util.Collection;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.ConcurrentMap;
    
    public class WebSocketMapUtil {
    
      public static ConcurrentMap<String, MyWebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    
      public static void put(String key, MyWebSocketServer myWebSocketServer){
           webSocketMap.put(key, myWebSocketServer);
        }
    
        public static MyWebSocketServer get(String key){
             return webSocketMap.get(key);
        }
    
        public static void remove(String key){
             webSocketMap.remove(key);
        }
     
        public static Collection<MyWebSocketServer> getValues(){
            return webSocketMap.values();
        }
    }

     

     客户端:

     1、添加Jar包依赖:

    <dependency>
      <groupId>org.java-websocket</groupId>
      <artifactId>Java-WebSocket</artifactId>
      <version>1.3.8</version>
    </dependency>

     2、创建Web Socket客户端类MyWebSocketClient,并继承WebSocketClient

     3、实现构造器,重写onOpenonCloseonMessageonError等方法

       

    实例代码:

    MyWebSocketClient 类

    import java.net.URI;
    import org.activiti.engine.impl.util.json.JSONObject;
    import org.apache.log4j.Logger;
    import org.java_websocket.client.WebSocketClient;
    import org.java_websocket.handshake.ServerHandshake;
    
    public class MyWebSocketClient extends WebSocketClient{
    
      Logger logger = Logger.getLogger(MyWebSocketClient.class);
     
      public MyWebSocketClient(URI serverUri) {
         super(serverUri);
      }
    
      @Override
      public void onOpen(ServerHandshake arg0) {
        // TODO Auto-generated method stub
        logger.info("------ MyWebSocket onOpen ------");
      }
    
      @Override
      public void onClose(int arg0, String arg1, boolean arg2) {
         // TODO Auto-generated method stub
         logger.info("------ MyWebSocket onClose ------");
      }
    
      @Override
      public void onError(Exception arg0) {
         // TODO Auto-generated method stub
         logger.info("------ MyWebSocket onError ------");
      }
    
      @Override
      public void onMessage(String arg0) {
         // TODO Auto-generated method stub
         logger.info("-------- 接收到服务端数据: " + arg0 + "--------");
      }
    }

     

    MyTest 测试类

    public class MyTest{
    
      public static void main(String[] arg0){
        MyWebSocketClient myClient = new MyWebSocketClient("此处为websocket服务端URI");
        // 往websocket服务端发送数据
        myClient.send("此为要发送的数据内容");
      }
    
    }

     

    转载于:https://www.cnblogs.com/jieerma666/p/10342435.html

    展开全文
  • 基于spring+spring MVC+mybatis框架的maven项目 https://www.cnblogs.com/jieerma666/p/10342435.html
  • C#WebSocket客户端服务端Demo,服务端采用SocketTCP通讯,WebSocket通讯传统通讯的差异就是多了一些消息解析,详情见服务端源代码!
  • [C#] WebSocket 客户端+服务端 轻松实现

    万次阅读 2017-07-05 14:40:59
     随着HTML5 WebSocket技术的日益成熟普及,我们可以借助WebSocket来更加方便地打通BSCS -- 因为B/S中的WebSocket可以直接连接到C/S的服务端,并进行双向通信。如下图所示:   一.对Socket Server的要求
  • WebSocket客户端服务端实例源码

    千次下载 热门讨论 2015-08-14 13:30:01
    WebSocket客户端服务端实例源码 WebSocket ws实例 HTML5 用java实现的服务端 Websocket服务器的正常通信 众所周知,Web 应用的交互过程通常是客户端通过浏览器发出一个请求,服务器端接收请求后进行处理并返回...
  • 定义  WebSocket是通过单个TCP连接提供全双工(双向通信)通信信道的计算机通信协议。此WebSocket API可在用户的浏览器和服务器之间进行双向通信。用户可以向服务器发送消息并接收事件驱动的响应...服务端代码 pom....
  • 需要安装 node.js 通过npm 安装 webSocket包 npm install websocket 客户端 var WebSocketClient = require('websocket').client;//获取websocketclient模块 var client = new WebSocketClient();//创建...
  • 实现了客户端与服务端之间建立长连接,通信 启动服务端 MyServer 启动客户端 client.html 启动客户端时,控制台打印出客户端已连接 客户端显示,与服务端连接已开启 刷新客户端 客户端与服务端重新建立连接 ...
  • Java Websocket实例【服务端与客户端实现全双工通讯】 现很多网站为了实现即时通讯,所用的技术都是轮询(polling)。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发 出HTTP request,然后...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,058
精华内容 423
关键字:

websocket客户端与服务端