说明:在java做服务端时,获取传过来的类名和方法名,使用java的反射机制得到相关的方法;
java为服务端,c#为客户端、Java为客户端
服务端-java
HelloController.java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String Hello(){
return "Hello";
}
}
WebsocketEntity.java
import lombok.Data;
@Data
public class WebsocketEntity {
String className;
String methodName;
}
MyWebSocketHandler.java
import com.alibaba.fastjson.JSON;
import com.foxconn.entity.WebsocketEntity;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.lang.reflect.Method;
public class MyWebSocketHandler extends TextWebSocketHandler {
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理接收到的消息
System.out.println("Received message: " + message.getPayload());
// 发送消息回客户端
//session.sendMessage(new TextMessage("Hello from server!"));
String response = "";
WebsocketEntity w = JSON.parseObject(message.getPayload(), WebsocketEntity.class);
response = callMethod(w.getClassName(),w.getMethodName());
session.sendMessage(new TextMessage(response));
}
private String callMethod(String className,String methodName) {
try {
Object controller = null;
Class<?> clazz = Class.forName("com.test.server."+className);
controller = clazz.newInstance();
Method method = controller.getClass().getMethod(methodName);
// 调用方法
return (String) method.invoke(controller);
} catch (Exception e) {
e.printStackTrace();
return "Error calling method";
}
}
// 其他方法,如handleTransportError、afterConnectionClosed等...
}
WebSocketConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler1(), "/hello1")
.setAllowedOrigins("*") // 允许所有来源的WebSocket连接(注意:在生产环境中应谨慎使用)
.addInterceptors(null); // 可选:添加拦截器
}
@Bean
public WebSocketHandler myHandler1() {
return new MyWebSocketHandler(); // 这里应该返回第一个Java方法的结果
}
// 其他配置...
}
客户端-java
MyWebSocketClient.java
import org.springframework.stereotype.Component;
import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
@ClientEndpoint
@Component
public class MyWebSocketClient {
Session session;
static MyWebSocketClient client;
private static BlockingQueue<String> messageQueue = new LinkedBlockingQueue<>();
static {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
client = new MyWebSocketClient();
try {
container.connectToServer(client, new URI("ws://ip:端口/hello1"));
} catch (DeploymentException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
System.out.println("Connected to server!");
// sendMessage("Hello, Server!");
}
@OnMessage
public void onMessage(String message, Session session) {
messageQueue.add(message);
System.out.println("Received from server: " + message);
}
public String sendMessage(String message) {
if (session != null && session.isOpen()) {
session.getAsyncRemote().sendText(message).toString();
}
return message;
}
public String test(String te){
String take="";
try {
client.sendMessage(te);
take= messageQueue.take();
} catch (Exception e) {
e.printStackTrace();
}
return take;
}
}
WebSocketClientController.java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class WebSocketClientController {
@Resource
private MyWebSocketClient client;
@GetMapping("/test")
public String connectToServer() {
String te = "{\"className\":\"HelloController\",\"methodName\":\"Hello\"}";
return client.test(te);
}
}
客户端-c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocket4Net;
namespace test1
{
class TestClient
{
static void Main(string[] args)
{
test();
Console.ReadLine();
}
public static async Task test()
{
// 创建一个WebSocket连接
var websocket = new WebSocket("ws://test:端口/hello1");
// 注册事件处理程序
websocket.Opened += (sender, e) =>
{
Console.WriteLine("WebSocket已打开");
websocket.Send("{\"className\":\"HelloController\",\"methodName\":\"Hello\"}");
};
websocket.Closed += (sender, e) => Console.WriteLine("WebSocket已关闭");
websocket.Error += (sender, e) => Console.WriteLine("WebSocket发生错误: " + e.Exception.Message);
websocket.MessageReceived += (sender, e) => Console.WriteLine("收到消息: " + e.Message);
// 异步打开WebSocket连接
await Task.Run(() => websocket.Open());
// 等待用户输入,以便在关闭WebSocket连接之前保持程序运行
Console.ReadLine();
// 异步关闭WebSocket连接
await Task.Run(() => websocket.Close());
}
}
}
c#为服务端,Java为客户端
服务端-c#
using System;
using System.Threading.Tasks;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace test1
{
class TestServer
{
static void Main(string[] args)
{
StartServer();
Console.ReadLine();
}
public static async Task StartServer()
{
var server = new WebSocketServer("ws://ip:端口");
server.AddWebSocketService<HelloController>("/hello1");
server.Start();
Console.WriteLine("WebSocket服务器已启动");
// 等待用户输入,以便在关闭WebSocket服务器之前保持程序运行
Console.ReadLine();
//server.Stop();
//Console.WriteLine("WebSocket服务器已关闭");
}
}
public class HelloController : WebSocketBehavior
{
protected override void OnMessage(MessageEventArgs e)
{
Console.WriteLine("收到消息: " + e.Data);
Send("{\"response\":\"Hello, client!\"}");
}
}
}