Unity3D客户端:
namespace LSocket.Net
{ /**
*
* @author feng侠,qq:313785443
* @date 2010-12-23
*
*/
// 描 述:封装c# socket数据传输协议
using UnityEngine;
using System;
using System.Net.Sockets;
using System.Net;
using System.Collections;
using System.Text;
using LSocket.Type;
using LSocket.cmd;
public class UnitySocket
{
public static Socket mSocket = null;
public UnitySocket()
{
}
public static void SocketConnection(string LocalIP, int LocalPort)
{
mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPAddress ip = IPAddress.Parse(LocalIP);
IPEndPoint ipe = new IPEndPoint(ip, LocalPort);
mSocket.Connect(ipe);
Send("<!policy-file-request>");//the second connect.if it's not equals policy head,it will come in the main connect!
Send(CommandID.LOGIN);
Send("feng");
string s=ReceiveString(100);//从服务器端接受返回信息
MonoBehaviour.print(s.Length);
MonoBehaviour.print(s);
}
catch (Exception e)
{
//ErrLog.RecordErr(e, ModuleName, "AsySocket", "");
}
}
public static void Send(short data)
{
byte[] longth=TypeConvert.getBytes(data,false);
mSocket.Send(longth);
}
public static void Send(long data)
{
byte[] longth=TypeConvert.getBytes(data,false);
mSocket.Send(longth);
}
public static void Send(int data)
{
byte[] longth=TypeConvert.getBytes(data,false);
mSocket.Send(longth);
}
public static void Send(string data)
{
byte[] longth=Encoding.UTF8.GetBytes(data);
mSocket.Send(longth);
}
public static short ReceiveShort()
{
byte[] recvBytes = new byte[2];
mSocket.Receive(recvBytes,2,0);//从服务器端接受返回信息
short data=TypeConvert.getShort(recvBytes,true);
return data;
}
public static int ReceiveInt()
{
byte[] recvBytes = new byte[4];
mSocket.Receive(recvBytes,4,0);//从服务器端接受返回信息
int data=TypeConvert.getInt(recvBytes,true);
return data;
}
public static long ReceiveLong()
{
byte[] recvBytes = new byte[8];
mSocket.Receive(recvBytes,8,0);//从服务器端接受返回信息
long data=TypeConvert.getLong(recvBytes,true);
return data;
}
public static string ReceiveString(int length)
{
byte[] recvBytes = new byte[length];
mSocket.Receive(recvBytes,length,0);//从服务器端接受返回信息
string data=Encoding.UTF8.GetString(recvBytes);
return data;
}
}
}
namespace LSocket.cmd
{
public class CommandID
{
/** 错误消息命令 **/
public static int ERROR = 1000;
/** 登陆消息命令 **/
public static int LOGIN = 1001;
/** 退出消息命令 **/
public static int EXIT = 1002;
/** 获取pdb文件消息命令 **/
public static int GETPDB= 1003;
public static int GETPDB_AGAIN = 1006;
/** 其他用户进入消息命令 **/
public static int OTHER_USERS = 1004;
public static int ACCEPT=1005;
public CommandID()
{
}
}
}
namespace LSocket.Type
{
using UnityEngine;
using System.Collections;
public class TypeConvert
{
public TypeConvert()
{
}
public static byte[] getBytes(short s, bool asc)
{
byte[] buf = new byte[2];
if (asc)
{
for (int i = buf.Length - 1; i >= 0; i--)
{
buf[i] = (byte) (s & 0x00ff);
s >>= 8;
}
}
else
{
for (int i = 0; i < buf.Length; i++)
{
buf[i] = (byte) (s & 0x00ff);
s >>= 8;
}
}
return buf;
}
public static byte[] getBytes(int s, bool asc)
{
byte[] buf = new byte[4];
if (asc)
for (int i = buf.Length - 1; i >= 0; i--)
{
buf[i] = (byte) (s & 0x000000ff);
s >>= 8;
}
else
for (int i = 0; i < buf.Length; i++)
{
buf[i] = (byte) (s & 0x000000ff);
s >>= 8;
}
return buf;
}
public static byte[] getBytes(long s, bool asc)
{
byte[] buf = new byte[8];
if (asc)
for (int i = buf.Length - 1; i >= 0; i--)
{
buf[i] = (byte) (s & 0x00000000000000ff);
s >>= 8;
}
else
for (int i = 0; i < buf.Length; i++)
{
buf[i] = (byte) (s & 0x00000000000000ff);
s >>= 8;
}
return buf;
}
public static short getShort(byte[] buf, bool asc) {
if (buf == null) {
//throw new IllegalArgumentException("byte array is null!");
}
if (buf.Length > 2) {
//throw new IllegalArgumentException("byte array size > 2 !");
}
short r = 0;
if (asc)
for (int i = buf.Length - 1; i >= 0; i--) {
r <<= 8;
r |= (short)(buf[i] & 0x00ff);
}
else
for (int i = 0; i < buf.Length; i++) {
r <<= 8;
r |= (short)(buf[i] & 0x00ff);
}
return r;
}
public static int getInt(byte[] buf, bool asc) {
if (buf == null) {
// throw new IllegalArgumentException("byte array is null!");
}
if (buf.Length > 4) {
//throw new IllegalArgumentException("byte array size > 4 !");
}
int r = 0;
if (asc)
for (int i = buf.Length - 1; i >= 0; i--) {
r <<= 8;
r |= (buf[i] & 0x000000ff);
}
else
for (int i = 0; i < buf.Length; i++) {
r <<= 8;
r |= (buf[i] & 0x000000ff);
}
return r;
}
public static long getLong(byte[] buf, bool asc) {
if (buf == null) {
//throw new IllegalArgumentException("byte array is null!");
}
if (buf.Length > 8) {
//throw new IllegalArgumentException("byte array size > 8 !");
}
long r = 0;
if (asc)
for (int i = buf.Length - 1; i >= 0; i--) {
r <<= 8;
r |= (buf[i] & 0x00000000000000ff);
}
else
for (int i = 0; i < buf.Length; i++) {
r <<= 8;
r |= (buf[i] & 0x00000000000000ff);
}
return r;
}
}
}
Java服务器端:
package com.unity.socket;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
/**
*
* @author feng侠
* @date 2010-12-23
*
*/
public class ByteSocketServer
{
//存放所有用户位置的map
private HashMap<String,User> userMap;
private ByteArrayOutputStream byteOutput;
private DataOutputStream output;
public ByteSocketServer()
{
userMap = new HashMap<String, User>();
}
/**
* @param args
*/
public static void main(String[] args)
{
new ByteSocketServer().startServer();
}
public void startServer()
{
try
{
ServerSocket serverSocket = new ServerSocket(843);
System.out.println("服务器开启");
//LoadPDB loadPDB=new LoadPDB();
while(true)
{
//新建一个连接
Socket socket = serverSocket.accept();
System.out.println("有用户登陆进来了");
//启动一条新的线程
//new UserThreadHandler(socket,userMap).start();
//byte[] b=new byte[22];
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
// PrintWriter pw=new PrintWriter(socket.getOutputStream());
byteOutput = new ByteArrayOutputStream();
output = new DataOutputStream(byteOutput);
char[] by=new char[22];
br.read(by,0,22);
String head=new String(by);
//String scmd=new String(by);
//System.out.println("命令号字符串:" + scmd+"ok");
if(head.equals("<policy-file-request/>"))
{
output.writeBytes(SecurityXML.GetXml()+"\0");
DataOutputStream dataOutput = new DataOutputStream(socket.getOutputStream());
//编写数据的长度
// dataOutput.writeLong(bytes.length);
System.out.print(head);
dataOutput.write(byteOutput.toByteArray());
dataOutput.flush();
socket.close();
// pw.write(SecurityXML.GetXml()+"\0");
// pw.flush();
}
else
{
new LoadPDB(socket,userMap).start();
}
}
}
catch (Exception e)
{
System.out.println("服务器出现异常!" + e);
}
}
}
package com.unity.socket;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import com.pdb.AnalyzePDB;
import com.unity.socket.type.ConvertType;
public class LoadPDB extends Thread
{
/** 错误消息命令 **/
public static final int ERROR = 1000;
/** 登陆消息命令 **/
public static final int LOGIN = 1001;
/** 退出消息命令 **/
public static final int EXIT = 1002;
/**获取pdb文件消息命令 **/
public static final int GETFILE = 1003;
/** 其他用户进入消息命令 **/
public static final int OTHER_USERS = 1004;
public static final int ACCEPT=1005;
private Socket socket;
//存放所有用户位置的map
private HashMap<String,User> userMap;
private User user;
private ByteArrayOutputStream byteOutput;
private DataOutputStream output;
int count=0;
private boolean first=true;
public LoadPDB(Socket socket,HashMap<String,User> userMap) throws IOException
{
this.socket = socket;
this.userMap = userMap;
}
public void run()
{
try
{
DataInputStream input = new DataInputStream(socket.getInputStream());
//这里就是解析协议的部分
while(true)
{
//读出开头长度的short(2个字节)
int cmd=0;
byte[] b=new byte[4];
input.read(b);
//String cmd=new String(b);
cmd=ConvertType.getInt(b,true);
System.out.println("命令号:" + cmd);
//根据cmd的值不同,判断后续的内容是什么
switch(cmd)
{
case LOGIN:
//读取用户名
System.out.println("读取用户名:" );
byte[] nameBytes=new byte[4];
input.read(nameBytes);
String userName = new String(nameBytes);
user = new User();
user.setName(userName);
user.setSocket(socket);
//判断该用户是否存在
if(userMap.containsKey(userName))
{
//用户名重复,发送回客户端
}
else
{
System.out.println("有新用户进入:" + userName);
userMap.put(userName, user);
initOutput();
String sReturn="It's ok to connect to server!";
byte[] bb=sReturn.getBytes();
output.write(bb, 0, bb.length);
sendMessage(socket,byteOutput.toByteArray());
}
break;
case GETFILE:
//获取分子文件
//String name= input.readUTF();
initOutput();
//读出len之后,接着是读取short类型的cmd(2个字节)
byte[] bb=new byte[4];
input.read(bb);
int type=ConvertType.getInt(bb, true);
System.out.println(type);
if(type==0)
{
byte[] bid=new byte[4];
input.read(bid);
String sid=new String(bid);
System.out.println("enter!");
// System.out.print(bis.);
File file=new File("d:/pdb/"+sid+".pdb");
if(!file.exists())
{
URL url=new URL("http://www.pdb.org/pdb/download/downloadFile.do?fileFormat=pdb&compression=NO&structureId="+sid);
URLConnection urlconn = url.openConnection(); //
HttpURLConnection httpconn = (HttpURLConnection)urlconn;
System.out.print(httpconn.HTTP_OK);
//InputStream in=url.openStream();
//InputStreamReader reader=new InputStreamReader(in);
BufferedInputStream bis=new BufferedInputStream(urlconn.getInputStream());
int s;
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(file));
String str = "";
while((s=bis.read())!=-1)
{
// str=str+Integer.toString(s);
bos.write(s);
// System.out.print(s);
// System.out.print(s);
}
System.out.print("ok");
bos.flush();
bos.close();
bis.close();
}
int number=AnalyzePDB.getAtoms(file);
// count++;
//int number=AnalyzePDB.alist.size();
byte[] bNumber=ConvertType.getBytes(number, false);
//System.out.print( bNumber.length);
// System.out.println("why?");
// DataOutputStream dataOutput = new DataOutputStream(socket.getOutputStream());
//编写数据的长度
// dataOutput.writeLong(bytes.length);
System.out.print(number);
// byte[] b0=output.
output.write(bNumber);
//dataOutput.write(byteOutput.toByteArray());
//dataOutput.flush();
sendMessage(socket,byteOutput.toByteArray());
//sendAllUser(byteOutput.toByteArray());
}
else
{
String atoms=(String) AnalyzePDB.alist.get(type-1);
System.out.print(atoms.getBytes().length);
output.writeBytes(atoms);
sendMessage(socket,byteOutput.toByteArray());
Thread.sleep(500);
}
break;
case ACCEPT:
initOutput();
output.writeShort(ACCEPT);
output.writeUTF(user.getName());
String ss=input.readUTF();
output.writeUTF(ss);
sendAllUser(byteOutput.toByteArray());
break;
default :break;
}
}
}
catch (Exception e)
{
//异常处理,当有用户异常退出时,向其他用户发出退出命令
//删除出现异常的username
if(!userMap.isEmpty())
{
try
{
System.out.println("发送该用户退出命令");
userExit();
}
catch (Exception ee)
{
System.out.println("用户退出异常!ee:" + ee);
}
}
System.out.println("线程错误:");
}
}
private void userExit() throws Exception
{
userMap.remove(user.getName());
initOutput();
output.writeShort(EXIT);
output.writeUTF(user.getName());
sendAllUser(byteOutput.toByteArray());
}
//重新初始化2个新的output
private void initOutput()
{
byteOutput = new ByteArrayOutputStream();
output = new DataOutputStream(byteOutput);
}
public void sendAllUser(byte[] bytes) throws Exception
{
for(Iterator<User> it = userMap.values().iterator(); it.hasNext();)
{
sendMessage(it.next().getSocket(),bytes);
}
}
/**
* 发送数据到网络流
* @param socket
* @param bytes
* @throws Exception
*/
public void sendMessage(Socket socket,byte[] bytes) throws Exception
{
DataOutputStream dataOutput = new DataOutputStream(socket.getOutputStream());
//编写数据的长度
// dataOutput.writeLong(bytes.length);
//System.out.print(bytes.length);
dataOutput.write(bytes);
dataOutput.flush();
}
public void sendUser(byte[] bytes,String name) throws Exception
{
User user=userMap.get(name);
sendMessage(user.getSocket(),bytes);
}
}
package com.unity.socket;
import java.net.Socket;
public class User
{
private String name;
private Socket socket;
private short x;
private short y;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Socket getSocket()
{
return socket;
}
public void setSocket(Socket socket)
{
this.socket = socket;
}
public short getX()
{
return x;
}
public void setX(short x)
{
this.x = x;
}
public short getY()
{
return y;
}
public void setY(short y)
{
this.y = y;
}
}
package com.unity.socket.type;
public class ConvertType
{
public ConvertType()
{
}
public final static byte[] getBytes(short s, boolean asc)
{
byte[] buf = new byte[2];
if (asc)
{
for (int i = buf.length - 1; i >= 0; i--)
{
buf[i] = (byte) (s & 0x00ff);
s >>= 8;
}
}
else
{
for (int i = 0; i < buf.length; i++)
{
buf[i] = (byte) (s & 0x00ff);
s >>= 8;
}
}
return buf;
}
public final static byte[] getBytes(int s, boolean asc) {
byte[] buf = new byte[4];
if (asc)
for (int i = buf.length - 1; i >= 0; i--) {
buf[i] = (byte) (s & 0x000000ff);
s >>= 8;
}
else
for (int i = 0; i < buf.length; i++) {
buf[i] = (byte) (s & 0x000000ff);
s >>= 8;
}
return buf;
}
public final static byte[] getBytes(long s, boolean asc) {
byte[] buf = new byte[8];
if (asc)
for (int i = buf.length - 1; i >= 0; i--) {
buf[i] = (byte) (s & 0x00000000000000ff);
s >>= 8;
}
else
for (int i = 0; i < buf.length; i++) {
buf[i] = (byte) (s & 0x00000000000000ff);
s >>= 8;
}
return buf;
}
public final static short getShort(byte[] buf, boolean asc)
{
if (buf == null)
{
throw new IllegalArgumentException("byte array is null!");
}
if (buf.length > 2)
{
throw new IllegalArgumentException("byte array size > 2 !");
}
short r = 0;
if (asc)
for (int i = buf.length - 1; i >= 0; i--) {
r <<= 8;
r |= (buf[i] & 0x00ff);
}
else
for (int i = 0; i < buf.length; i++) {
r <<= 8;
r |= (buf[i] & 0x00ff);
}
return r;
}
public final static int getInt(byte[] buf, boolean asc) {
if (buf == null) {
throw new IllegalArgumentException("byte array is null!");
}
if (buf.length > 4) {
throw new IllegalArgumentException("byte array size > 4 !");
}
int r = 0;
if (asc)
for (int i = buf.length - 1; i >= 0; i--) {
r <<= 8;
r |= (buf[i] & 0x000000ff);
}
else
for (int i = 0; i < buf.length; i++) {
r <<= 8;
r |= (buf[i] & 0x000000ff);
}
return r;
}
public final static long getLong(byte[] buf, boolean asc) {
if (buf == null) {
throw new IllegalArgumentException("byte array is null!");
}
if (buf.length > 8) {
throw new IllegalArgumentException("byte array size > 8 !");
}
long r = 0;
if (asc)
for (int i = buf.length - 1; i >= 0; i--) {
r <<= 8;
r |= (buf[i] & 0x00000000000000ff);
}
else
for (int i = 0; i < buf.length; i++) {
r <<= 8;
r |= (buf[i] & 0x00000000000000ff);
}
return r;
}
}
分享到:
相关推荐
Unity socket与java 服务器端进行通信详细代码
在实际开发中,Unity3D与Java间的Socket通信可能会遇到网络延迟、数据包丢失等问题,因此需要实现心跳机制以检测连接状态,以及错误处理机制来确保系统的稳定性和可靠性。此外,为了防止数据安全问题,可能还需要...
Unity3D的UnityWebRequest API虽然提供了更高级别的HTTP通信方式,但在这里并不适用,因为我们需要更低级别的TCP/IP通信和自定义的Protobuf协议。 总之,实现Unity3D与Java之间的Protobuf通信涉及客户端的C#编程、...
在Android Studio中,我们可以使用`java.net.Socket`和`java.net.ServerSocket`类来实现Socket通信。首先,服务器端创建`ServerSocket`监听特定端口,等待客户端连接。然后,客户端使用`Socket`对象连接到服务器,...
标题中的“基于Netty,Socket通信的斗地主游戏服务,前台使用Unity3d&C#,后台Java实现”表明这是一个综合性的项目,涉及到网络通信、游戏开发以及前后端交互等多个技术领域。下面将详细阐述其中涉及的关键知识点: 1....
5. 网络通信:Unity3D支持多种网络通信方式,如UnityWebRequest、WebGL Socket等,适用于多人在线游戏或实时数据交换。 6. 用户界面(UI):Unity的UI系统(UGUI)可以创建复杂的交互界面,配合Canvas和Rect...
unity3d 游戏客户端源码,主要的功能有: 1. 实现C#与Java Web服务的通信 2. 使用Netty实现Socket异步长连接游戏服务器 3. 解决了网络通信的断包粘包问题 4. 实现了消息的序列化与反序列化 5. 实现客户端连接认证 6....
在本文中,我们将深入探讨Socket通信的基本概念、工作原理以及如何利用Java和Unity3D来构建一个简单的聊天应用。 一、Socket通信基础 1. Socket定义:Socket是操作系统提供的网络编程接口,它为应用程序提供了一种...
在IT行业中,游戏开发是一个非常活跃的领域,而Unity作为一款强大的跨平台游戏引擎,被广泛应用于2D、3D游戏开发。为了实现高效的数据通信,开发者常常会结合其他技术,如Netty和ProtoBuf。本篇文章将深入探讨如何在...
在这个项目中,Leaf Server被用作Go语言的游戏服务器框架,处理Unity3D客户端的Socket通信。 4. **protobuf(Protocol Buffers)**:protobuf是Google推出的一种数据序列化协议,用于结构化数据的编码和解码,可以...
- **3D引擎**:Unity3D、Three.js等都是优秀的开源选项。 - **模型格式**:FBX、GLTF等通用格式有利于跨平台兼容。 - **网络库**:Socket.IO、Netty等可用于构建高效稳定的网络连接。 #### 开发流程建议 1. **需求...
5. **网络编程**:Java提供Socket编程接口,用于创建客户端和服务器之间的通信,这是网络游戏实现玩家交互的基础。 6. **图形用户界面(GUI)**:虽然网游主要是基于Web的,但理解Swing或JavaFX等库可以构建本地...
开发者可能使用Unity3D或Unreal Engine进行跨平台游戏开发,结合Java做后端服务器实现,例如使用Netty处理网络通信。 以上各项目涵盖了Java Web开发、数据库管理、用户界面设计、网络编程、分布式系统等多个方面,...
JavaME中的JSR 82(Java Bluetooth API)和JSR 118(Java.comm API)可用于蓝牙和串口通信,而HttpConnection或Socket类则用于HTTP请求和TCP/IP连接,实现服务器交互。 4. **游戏逻辑与动画**:开发者需要掌握如何...
此外,还要熟悉图形库,例如Java AWT和Swing用于桌面游戏,或者LibGDX、Unity3D等跨平台框架用于更复杂的游戏开发。对于网络编程,你需要了解Socket编程,以便让游戏中的玩家能够在线互动。 总之,这份"java游戏...
LibGDX是一个开源的Java框架,适用于2D和简单的3D游戏开发,提供了丰富的图形、音频和输入处理功能。 4. **OpenGL ES**: 对于复杂的3D游戏,开发者通常会使用OpenGL ES,这是Android支持的图形库,用于实现高性能的...
Java的Socket编程用于实现客户端-服务器通信,处理玩家之间的交互和同步。 9. **性能优化**:手机资源有限,因此性能优化至关重要。这包括内存管理、减少渲染开销、优化算法和数据结构等。 10. **调试与测试**:...
尽管Java可能不如C++或Unity等专业游戏引擎常见,但它依然能够创建引人入胜的2D和简单的3D游戏。在“沙丘城堡”这个项目中,开发者可能使用了自定义的游戏引擎或者Java Swing或JavaFX库来构建游戏界面和交互逻辑。 ...
4. **图形渲染**:在Java手机游戏中,图形渲染涉及2D或3D图形的创建和显示。OpenGL ES是Android系统中的标准图形库,用于实现复杂的图形效果和动画。 5. **用户界面(UI)设计**:UI设计决定了玩家与游戏的交互方式...