Unity3dsocket和javasocket通信byfeng侠.doc_第1页
Unity3dsocket和javasocket通信byfeng侠.doc_第2页
Unity3dsocket和javasocket通信byfeng侠.doc_第3页
Unity3dsocket和javasocket通信byfeng侠.doc_第4页
Unity3dsocket和javasocket通信byfeng侠.doc_第5页
已阅读5页,还剩19页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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();/the second connect.if its 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 byte2; mSocket.Receive(recvBytes,2,0);/从服务器端接受返回信息 short data=TypeConvert.getShort(recvBytes,true); return data;public static int ReceiveInt() byte recvBytes = new byte4; mSocket.Receive(recvBytes,4,0);/从服务器端接受返回信息 int data=TypeConvert.getInt(recvBytes,true); return data;public static long ReceiveLong() byte recvBytes = new byte8; mSocket.Receive(recvBytes,8,0);/从服务器端接受返回信息 long data=TypeConvert.getLong(recvBytes,true);return data;public static string ReceiveString(int length) byte recvBytes = new bytelength; mSocket.Receive(recvBytes,length,0);/从服务器端接受返回信息 string data=Encoding.UTF8.GetString(recvBytes); return data;namespace LSocket.cmdpublic 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.Typeusing UnityEngine;using System.Collections;public class TypeConvert public TypeConvert()public static byte getBytes(short s, bool asc) byte buf = new byte2; if (asc) for (int i = buf.Length - 1; i = 0; i-) bufi = (byte) (s & 0x00ff); s = 8; else for (int i = 0; i = 8; return buf;public static byte getBytes(int s, bool asc) byte buf = new byte4; if (asc) for (int i = buf.Length - 1; i = 0; i-) bufi = (byte) (s & 0x000000ff); s = 8; else for (int i = 0; i = 8; return buf; public static byte getBytes(long s, bool asc) byte buf = new byte8; if (asc) for (int i = buf.Length - 1; i = 0; i-) bufi = (byte) (s & 0x00000000000000ff); s = 8; else for (int i = 0; i = 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)(bufi & 0x00ff); else for (int i = 0; i buf.Length; i+) r 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 |= (bufi & 0x000000ff); else for (int i = 0; i buf.Length; i+) r 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 |= (bufi & 0x00000000000000ff); else for (int i = 0; i buf.Length; i+) r = 8; r |= (bufi & 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 .ServerSocket;import .Socket;import java.util.HashMap;/* * * author feng侠 * date 2010-12-23 * */public class ByteSocketServer/存放所有用户位置的mapprivate HashMap userMap;private ByteArrayOutputStream byteOutput;private DataOutputStream output;public ByteSocketServer()userMap = new HashMap();/* * param args */public static void main(String args)new ByteSocketServer().startServer();public void startServer()tryServerSocket 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 byte22;BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream(); / PrintWriter pw=new PrintWriter(socket.getOutputStream(); byteOutput = new ByteArrayOutputStream();output = new DataOutputStream(byteOutput); char by=new char22; br.read(by,0,22); String head=new String(by); /String scmd=new String(by);/System.out.println(命令号字符串: + scmd+ok); if(head.equals() 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(); elsenew 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 .HttpURLConnection;import .MalformedURLException;import .Socket;import .URL;import .URLConnection;import java.util.Iterator;import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import .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 intEXIT = 1002;/*获取pdb文件消息命令 */public static final intGETFILE = 1003;/* 其他用户进入消息命令 */public static final int OTHER_USERS = 1004;public static final int ACCEPT=1005;private Socket socket;/存放所有用户位置的mapprivate HashMap userMap;private User user;private ByteArrayOutputStream byteOutput;private DataOutputStream output; int count=0;private boolean first=true;public LoadPDB(Socket socket,HashMap userMap) throws IOExceptionthis.socket = socket;this.userMap = userMap;public void run()tryDataInputStream input = new DataInputStream(socket.getInputStream();/这里就是解析协议的部分while(true)/读出开头长度的short(2个字节)int cmd=0;byte b=new byte4;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 byte4;input.read(nameBytes);String userName = new String(nameBytes);user = new User();user.setName(userName);user.setSocket(socket);/判断该用户是否存在if(userMap.containsKey(userName)/用户名重复,发送回客户端elseSystem.out.println(有新用户进入: + userName);userMap.put(userName, user);initOutput();String sReturn=Its 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 byte4;input.read(bb);int type=ConvertType.getInt(bb, true); System.out.println(type);if(type=0)byte bid=new byte4;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(/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();elseString 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)/异常处理,当有用户异常退出时,向其他用户发出退出命令/删除出现异常的usernameif(!userMap.isEmpty()trySystem.out.println(发送该用户退出命令);userExit();catch (Exception ee)System.out.println(用户退出异常!ee: + ee);System.out.println(线程错误:);private void userExit() throws ExceptionuserMap.remove(user.getName();initOutput();output.writeShort(EXIT);output.writeUTF(user.getName();sendAllUser(byteOutput.toByteArray();/重新初始化2个新的outputprivate void initOutput()byteOutput = new ByteArrayOutputStream();output = new DataOutputStream(byteOutput);public void sendAllUser(byte bytes) throws Exceptionfor(Iterator 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 ExceptionDataOutputStream 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 .Socket;public class Userprivate String name;private Socket socket;private short x;private short y;public String getName()return name;public void setName(String 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 byte2; if (asc) for (int

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论