当前位置: 首页 > news >正文

c# websocket client java websocket server

实现功能:c# websocket 客户端 连接 java websocket 服务端

一,c# websocket 客户端 

nuget websocketsharp-netstandard

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocketSharp;  //websocketsharp-netstandard

namespace websocketClientTest
{
    public class Program
    {
        static void Main(string[] args)
        {
            string webPath = "ws://192.168.1.100:8080/websocket";
            WebSocket webSocket = new WebSocket(webPath);
            webSocket.Connect();            
            webSocket.OnMessage += (sender, e) =>
            {
                //接收到消息并处理                
                byte[] byteArray = e.RawData;
                string str = System.Text.Encoding.UTF8.GetString(byteArray);
                Console.WriteLine(str);
            };

            string strMsg = "hello"; 
            webSocket.Send(System.Text.Encoding.Default.GetBytes(strMsg));//发送消息的函数
            while (true)
            {
               Thread.Sleep(5000);
            }
        }

        public Program(string url)
        {
            
        }                
    }
}

二,java websocket server

import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * @ServerEndpoint
 * 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint(value="/websocket")
@Component
public class WebSocketTest {
    
    private static ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
    
    @OnOpen
    public void onOpen(Session session){ 
        System.out.println("加入连接");  
        sessions.put(session.getId(), session);
    }

    @OnClose
    public void onClose(){ 
        System.out.println("关闭连接");
        
    }

    @OnError
    public void onError(Session session, Throwable error){  
       System.out.println("发生错误");
       error.printStackTrace(); 
       //TODO
    }

    /**
     * 收到客户端消息后调用的方法
     * @param messages 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage(maxMessageSize = 5000000)
    public void onMessage(byte[] messages, Session session) {
        try {
            System.out.println("接收到消息:"+new String(messages,"utf-8"));
            //返回信息
            String resultStr="{name:\"张三\",age:18,addr:\"上海浦东\"}";
            //发送字符串信息的 byte数组
            ByteBuffer bf=ByteBuffer.wrap(resultStr.getBytes("utf-8"));
            session.getBasicRemote().sendBinary(bf);
            //发送字符串
            //session.getBasicRemote().sendText("测试"); 
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

http://www.lryc.cn/news/94917.html

相关文章:

  • 【玩转循环】探索Python中的无限可能性
  • 网安学习经历小记
  • MyBatis之慎用association
  • 【Java/大数据】Kafka简介
  • 【动手学深度学习】读写文件
  • http-server 的安装与使用
  • SQL高级教程
  • 9.pixi.js编写的塔防游戏(类似保卫萝卜)-群炮弹发射逻辑
  • 分布式链路追踪
  • 计算机网络————网络层
  • el-table刷新后保持高亮并改变状态字段
  • ARM Ubuntu内核更新记录
  • 【sgUploadTray】上传托盘自定义组件,可实时查看上传列表进度
  • 改进二进制粒子群算法在配电网重构中的应用(Matlab实现)【论文复现】
  • 【文章系列解读】Nerf
  • 基于springboot,vue网上订餐系统
  • Nautilus Chain 更换全新测试网,主网即将在不久上线
  • 攻防世界web:Web_php_wrong_nginx_config,python3后门
  • 【VUE】解决图片视频加载缓慢/首屏加载白屏的问题
  • spring复习:(35)在getBean时,在哪里根据普通bean和工厂bean进行区分处理来返回的?
  • Jenkins全栈体系(二)
  • c++11 标准模板(STL)(std::basic_istream)(九)
  • OpenSource - Spring Startup Ananlyzer
  • ES6迭代器、Set、Map集合和async异步函数
  • mac android studio设置跟mac系统一样的快捷键
  • Java-通过IP获取真实地址
  • Java代码实现word转PDF
  • Java设计模式-简单工厂(Simple Factory)模式
  • 微软所有业务线梳理
  • SDN系统方法 | 1. 概述