Unity3d使用Socket与java服务器通信
程序员文章站
2022-03-26 14:40:19
...
转自:https://blog.csdn.net/AngelMyMei/article/details/40742825
---------------------------客户端----------------------------------------
-
using System;
-
using System.Collections.Generic;
-
using System.Linq;
-
using System.Text;
-
using System.Net;
-
using System.Net.Sockets;
-
using System.Threading;
-
using UnityEngine;
-
-
-
/*
-
*
-
*Socket客户端通信类
-
*
-
* lm
-
*/
-
public class SocketHelper
-
{
-
-
private static SocketHelper socketHelper=new SocketHelper();
-
-
private Socket socket;
-
-
-
//饿汉模式
-
public static SocketHelper GetInstance()
-
{
-
return socketHelper;
-
}
-
-
private SocketHelper() {
-
-
//采用TCP方式连接
-
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-
-
//服务器IP地址
-
IPAddress address = IPAddress.Parse("127.0.0.1");
-
-
//服务器端口
-
IPEndPoint endpoint = new IPEndPoint(address,8000);
-
-
//异步连接,连接成功调用connectCallback方法
-
IAsyncResult result = socket.BeginConnect(endpoint, new AsyncCallback(ConnectCallback), socket);
-
-
//这里做一个超时的监测,当连接超过5秒还没成功表示超时
-
bool success = result.AsyncWaitHandle.WaitOne(5000, true);
-
if (!success)
-
{
-
//超时
-
Closed();
-
Debug.Log("connect Time Out");
-
}
-
else
-
{
-
//与socket建立连接成功,开启线程接受服务端数据。
-
Thread thread = new Thread(new ThreadStart(ReceiveSorket));
-
thread.IsBackground = true;
-
thread.Start();
-
}
-
-
}
-
-
private void ConnectCallback(IAsyncResult asyncConnect)
-
{
-
Debug.Log("connect success");
-
}
-
-
private void ReceiveSorket()
-
{
-
//在这个线程中接受服务器返回的数据
-
while (true)
-
{
-
-
if (!socket.Connected)
-
{
-
//与服务器断开连接跳出循环
-
Debug.Log("Failed to clientSocket server.");
-
socket.Close();
-
break;
-
}
-
try
-
{
-
//接受数据保存至bytes当中
-
byte[] bytes = new byte[4096];
-
//Receive方法中会一直等待服务端回发消息
-
//如果没有回发会一直在这里等着。
-
int i = socket.Receive(bytes);
-
if (i <= 0)
-
{
-
socket.Close();
-
break;
-
}
-
Debug.Log(System.Text.Encoding.Default.GetString(bytes));
-
}
-
catch (Exception e)
-
{
-
Debug.Log("Failed to clientSocket error." + e);
-
socket.Close();
-
break;
-
}
-
}
-
}
-
-
-
-
//关闭Socket
-
public void Closed()
-
{
-
if (socket != null && socket.Connected)
-
{
-
socket.Shutdown(SocketShutdown.Both);
-
socket.Close();
-
}
-
socket = null;
-
}
-
-
-
-
//向服务端发送一条字符串
-
//一般不会发送字符串 应该是发送数据包
-
public void SendMessage(string str)
-
{
-
byte[] msg = Encoding.UTF8.GetBytes(str);
-
-
if (!socket.Connected)
-
{
-
socket.Close();
-
return;
-
}
-
try
-
{
-
IAsyncResult asyncSend = socket.BeginSend(msg, 0, msg.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
-
bool success = asyncSend.AsyncWaitHandle.WaitOne(5000, true);
-
if (!success)
-
{
-
socket.Close();
-
Debug.Log("Failed to SendMessage server.");
-
}
-
}
-
catch
-
{
-
Debug.Log("send message error");
-
}
-
}
-
-
-
-
private void SendCallback(IAsyncResult asyncConnect)
-
{
-
Debug.Log("send success");
-
}
-
-
-
}
----------------------------------服务器-------------------------------------------------
-
package org.u3d.server;
-
-
import java.io.BufferedInputStream;
-
import java.io.IOException;
-
import java.net.ServerSocket;
-
import java.net.Socket;
-
-
-
/**
-
*
-
* unity3d 服务端
-
*
-
*
-
*
-
* @author lm
-
*
-
*/
-
public class U3dServer implements Runnable {
-
-
public void run() {
-
-
ServerSocket u3dServerSocket = null;
-
-
while(true){
-
-
try {
-
-
u3dServerSocket=new ServerSocket(8000);
-
-
System.out.println("u3d服务已经启动,监听8000端口");
-
-
while (true) {
-
Socket socket = u3dServerSocket.accept();
-
System.out.println("客户端接入");
-
new RequestReceiver(socket).start();
-
}
-
-
-
} catch (IOException e) {
-
System.err.println("服务器接入失败");
-
if (u3dServerSocket != null) {
-
try {
-
u3dServerSocket.close();
-
} catch (IOException ioe) {
-
}
-
u3dServerSocket = null;
-
}
-
}
-
-
// 服务延时重启
-
try {
-
Thread.sleep(5000);
-
} catch (InterruptedException e) {
-
-
}
-
-
}
-
-
-
}
-
-
-
-
/**
-
* 客户端请求接收线程
-
* @author lm
-
*
-
*/
-
class RequestReceiver extends Thread {
-
-
/** 报文长度字节数 */
-
private int messageLengthBytes = 1024;
-
-
private Socket socket;
-
-
/** socket输入处理流 */
-
private BufferedInputStream bis = null;
-
-
-
public RequestReceiver(Socket socket) {
-
this.socket = socket;
-
}
-
-
@Override
-
public void run() {
-
try {
-
bis = new BufferedInputStream(socket.getInputStream());
-
byte[] buf = new byte[messageLengthBytes];
-
-
/**
-
* 在Socket报文传输过程中,应该明确报文的域
-
*/
-
while (true) {
-
-
/*
-
* 这种业务处理方式是根据不同的报文域,开启线程,采用不同的业务逻辑进行处理
-
* 依据业务需求而定
-
*/
-
//new RequestHandler(socket, buf).start();
-
bis.read(buf);
-
System.out.println(new String(buf,"utf-8"));
-
Message msg=new GeneralMessage("i am server");
-
msg.write(socket.getOutputStream());
-
}
-
-
} catch (IOException e) {
-
System.err.println("读取报文出错");
-
} finally {
-
if (socket != null) {
-
try {
-
socket.close();
-
} catch (IOException e) {
-
}
-
socket = null;
-
}
-
}
-
-
}
-
}
-
-
-
/**
-
* 描述: 请求处理器
-
*
-
*/
-
/* class RequestHandler extends Thread {
-
-
-
-
-
}
-
*/
-
-
}
-
<pre name="code" class="java">public class U3dApplication {
-
-
private static U3dApplication instance = null;
-
-
private boolean stop;
-
-
private U3dApplication() {
-
}
-
-
public static synchronized U3dApplication getApplication() {
-
if (instance == null) {
-
instance = new U3dApplication();
-
}
-
return instance;
-
}
-
-
public void start() {
-
init();
-
new Thread(new U3dServer(), "U3d Server").start();
-
-
while (!stop) {
-
try {
-
Thread.sleep(1000);
-
} catch (InterruptedException e) {
-
}
-
}
-
}
-
-
/**
-
* @param args
-
*/
-
public static void main(String[] args) {
-
Runtime.getRuntime().addShutdownHook(new Thread() {
-
@Override
-
public void run() {
-
getApplication().stopMe();
-
}
-
});
-
getApplication().start();
-
}
-
-
public void stopMe() {
-
System.out.println("系统即将关闭...");
-
}
-
-
-
/**
-
* 初始化系统
-
*/
-
private void init() {
-
-
}
-
-
}