c# websocket client java websocket server

本文展示了如何使用C#的WebSocketSharp库创建一个客户端,连接到运行在Java环境下的WebSocket服务器端。C#客户端代码包括建立连接、接收和发送消息的实现,而Java服务器端则使用Spring框架的@ServerEndpoint注解进行配置,处理打开、关闭、错误事件以及接收和响应消息。
摘要由CSDN通过智能技术生成

实现功能: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();
        }
    }
    

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值