Java+Unity实现简单通信
Java+Unity实现简单通信
原本准备实现
后端:java+spring+netty+mysql
但由于很久没有使用sql,便只使用了java+spring+netty的解决方案。
内容实现为简单的查询和登录功能。
后端实现
使用了spring webflux框架
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
Bean:userbean储存信息
public class UserBean {
private String name;
private String passWord;
public UserBean(String name, String passWord) {
super();
this.name = name;
this.passWord = passWord;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
@Override
public String toString() {
return "UserBean [name=" + name + ", passWord=" + passWord + "]";
}
}
这里没有使用server层和dao层,只写了control层相应请求。
@RestController
public class GameService {
@CrossOrigin
@GetMapping("/hello")
public String hello() {
return "hello";
}
//登录
@PostMapping("/login")
public boolean login(UserBean userBean) {
System.out.println(userBean);
//登录信息必须为账号123,密码123456,才认证成功
if(userBean.getName().equals("123") && userBean.getPassWord().equals("123456")) {
return true;
}else {
return false;
}
}
//注册
@PutMapping("/register")
public boolean register(@RequestBody UserBean userBean) {
System.out.println(userBean);
return true;
}
//获取用户列表
@GetMapping("/user")
@ResponseBody
public ArrayList<UserBean> getUsers() {
UserBean user1 = new UserBean("123465", "aaaa");
UserBean user2 = new UserBean("zzzz", "aaaa");
ArrayList<UserBean> list = new ArrayList<UserBean>();
list.add(user1);
list.add(user2);
return list;
}
}
webflux的过滤器,可以实现一些过滤功能,这里仅测试用
//@Component
@Configuration
public class TestServletFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
// TODO Auto-generated method stub
System.out.println("新的请求");
exchange.getSession().doOnNext(t -> {
System.out.println(t.getId());
});
System.out.println(exchange.getRequest().getPath());
System.out.println(exchange.getResponse().getStatusCode());
System.out.println(exchange.getSession().subscribe(t -> {
System.out.println(t.getId());
t.save();
}));
return chain.filter(exchange);
}
}
unity
搭建ui
登录
注册
列表
制作相应的ui控制脚本,这里只展示UnityWebRequest的使用,由web管理组件控制。
public class WebSocketManager : MonoBehaviour
{
//UI管理器引用
public UIManager uIManager;
//web管理器唯一引用,以便其他对象引用
public static WebSocketManager socketManager;
//host
public string host = "http://127.0.0.1";
void Start()
{
//单例
if(socketManager!= null)
{
Destroy(gameObject);
}
else
{
socketManager = this;
}
}
//登录
public void login(string name, string pw)
{
StartCoroutine(_login(name, pw));
}
//登录的协程
public IEnumerator _login(string name,string pw)
{
string url = host + "/login";
//创建表单数据,发送请求
List<IMultipartFormSection> fromData = new List<IMultipartFormSection>();
fromData.Add(new MultipartFormDataSection("name", name));
fromData.Add(new MultipartFormDataSection("passWord", pw));
UnityWebRequest request =UnityWebRequest.Post(url,fromData);
yield return request.SendWebRequest();
if(request.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning("请求失败:"+request.error);
}
else
{
Debug.Log(request.downloadHandler.text);
bool isLogin = bool.Parse(request.downloadHandler.text);
//请求为ture后跳转至主页面
if (isLogin)
{
uIManager.OpenMain();
}
}
}
//获得多个用户
public void getuser()
{
StartCoroutine(_getUser());
}
//获得多个用户的协程
IEnumerator _getUser()
{
string url = host+"/user";
UnityWebRequest request = UnityWebRequest.Get(url);
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning("请求失败:" + request.error);
}
else
{
Debug.Log(request.downloadHandler.text);
//使用jsonNet将list的json数据转换为list对象
List<UserBean> users = JsonConvert.DeserializeObject<List<UserBean>>(request.downloadHandler.text);
//unity自带的json转换器不能转换list对象
//List<UserBean> users = JsonUtility.FromJson<List<UserBean>>(request.downloadHandler.text);
//主页面数据更新
uIManager.main.updataUserData(users);
}
}
//注册
public void regist(string name, string pw)
{
StartCoroutine(_register(name, pw));
}
//注册的协程
IEnumerator _register(string name,string pw)
{
string url =host+ "/register";
UserBean user = new UserBean();
user.name = name;
user.passWord = pw;
string data = JsonUtility.ToJson(user);
Debug.Log("发送信息:" + data);
//发送put请求,并将改写contentType
UnityWebRequest request = UnityWebRequest.Put(url, data);
request.uploadHandler.contentType = "application/json";
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning("请求失败:" + request.error);
}
else
{
Debug.Log(request.downloadHandler.text);
bool isRigster = bool.Parse(request.downloadHandler.text);
//注册成功,跳转至登录页面
if (isRigster)
{
uIManager.OpenLogin();
}
}
}
}
演示效果:
整体上,没有什么难度,只是在netty中没有session,花了很大的时间才发现为什么sessionID一直在变,对于netty需要自己去实现sessionID的细节来保持会话。