实现功能: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
}文章来源:https://www.toymoban.com/news/detail-574003.html
/**
* 收到客户端消息后调用的方法
* @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();
}
}
} 文章来源地址https://www.toymoban.com/news/detail-574003.html
到了这里,关于c# websocket client java websocket server的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!