UNITY之使用Socket与java服务器通信

---------------------------客户端----------------------------------------

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Net;  
  6. using System.Net.Sockets;  
  7. using System.Threading;  
  8. using UnityEngine;  
  9.   
  10.   
  11. /* 
  12.  *  
  13.  *Socket客户端通信类 
  14.  *  
  15.  * lm 
  16.  */  
  17. public class SocketHelper  
  18. {  
  19.   
  20.     private static SocketHelper socketHelper=new SocketHelper();  
  21.   
  22.     private Socket socket;  
  23.   
  24.   
  25.     //饿汉模式  
  26.     public static SocketHelper GetInstance()  
  27.     {  
  28.         return socketHelper;  
  29.     }  
  30.   
  31.     private SocketHelper() {  
  32.   
  33.         //采用TCP方式连接  
  34.         socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
  35.   
  36.         //服务器IP地址  
  37.         IPAddress address = IPAddress.Parse("127.0.0.1");  
  38.   
  39.         //服务器端口  
  40.         IPEndPoint endpoint = new IPEndPoint(address,8000);  
  41.   
  42.         //异步连接,连接成功调用connectCallback方法  
  43.         IAsyncResult result = socket.BeginConnect(endpoint, new AsyncCallback(ConnectCallback), socket);  
  44.   
  45.         //这里做一个超时的监测,当连接超过5秒还没成功表示超时  
  46.         bool success = result.AsyncWaitHandle.WaitOne(5000, true);  
  47.         if (!success)  
  48.         {  
  49.             //超时  
  50.             Closed();  
  51.             Debug.Log("connect Time Out");  
  52.         }  
  53.         else  
  54.         {  
  55.             //与socket建立连接成功,开启线程接受服务端数据。  
  56.             Thread thread = new Thread(new ThreadStart(ReceiveSorket));  
  57.             thread.IsBackground = true;  
  58.             thread.Start();  
  59.         }  
  60.   
  61.     }  
  62.   
  63.     private void ConnectCallback(IAsyncResult asyncConnect)  
  64.     {  
  65.         Debug.Log("connect success");  
  66.     }  
  67.   
  68.     private void ReceiveSorket()  
  69.     {  
  70.         //在这个线程中接受服务器返回的数据  
  71.         while (true)  
  72.         {  
  73.   
  74.             if (!socket.Connected)  
  75.             {  
  76.                 //与服务器断开连接跳出循环  
  77.                 Debug.Log("Failed to clientSocket server.");  
  78.                 socket.Close();  
  79.                 break;  
  80.             }  
  81.             try  
  82.             {  
  83.                 //接受数据保存至bytes当中  
  84.                 byte[] bytes = new byte[4096];  
  85.                 //Receive方法中会一直等待服务端回发消息  
  86.                 //如果没有回发会一直在这里等着。  
  87.                 int i = socket.Receive(bytes);  
  88.                 if (i <= 0)  
  89.                 {  
  90.                     socket.Close();  
  91.                     break;  
  92.                 }  
  93.                 Debug.Log(System.Text.Encoding.Default.GetString(bytes));  
  94.             }  
  95.             catch (Exception e)  
  96.             {  
  97.                 Debug.Log("Failed to clientSocket error." + e);  
  98.                 socket.Close();  
  99.                 break;  
  100.             }  
  101.         }  
  102.     }  
  103.   
  104.   
  105.   
  106.     //关闭Socket  
  107.     public void Closed()  
  108.     {  
  109.         if (socket != null && socket.Connected)  
  110.         {  
  111.             socket.Shutdown(SocketShutdown.Both);  
  112.             socket.Close();  
  113.         }  
  114.         socket = null;  
  115.     }  
  116.   
  117.   
  118.   
  119.     //向服务端发送一条字符串  
  120.     //一般不会发送字符串 应该是发送数据包  
  121.     public void SendMessage(string str)  
  122.     {  
  123.         byte[] msg = Encoding.UTF8.GetBytes(str);  
  124.   
  125.         if (!socket.Connected)  
  126.         {  
  127.             socket.Close();  
  128.             return;  
  129.         }  
  130.         try  
  131.         {  
  132.             IAsyncResult asyncSend = socket.BeginSend(msg, 0, msg.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);  
  133.             bool success = asyncSend.AsyncWaitHandle.WaitOne(5000, true);  
  134.             if (!success)  
  135.             {  
  136.                 socket.Close();  
  137.                 Debug.Log("Failed to SendMessage server.");  
  138.             }  
  139.         }  
  140.         catch  
  141.         {  
  142.             Debug.Log("send message error");  
  143.         }  
  144.     }  
  145.   
  146.   
  147.   
  148.     private void SendCallback(IAsyncResult asyncConnect)  
  149.     {  
  150.         Debug.Log("send success");  
  151.     }  
  152.   
  153.   
  154. }  

----------------------------------服务器-------------------------------------------------

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package org.u3d.server;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.IOException;  
  5. import java.net.ServerSocket;  
  6. import java.net.Socket;  
  7.   
  8.   
  9. /** 
  10.  *  
  11.  * unity3d 服务端 
  12.  *  
  13.  *  
  14.  *  
  15.  * @author lm 
  16.  * 
  17.  */  
  18. public class U3dServer implements Runnable {  
  19.   
  20.     public void run() {  
  21.           
  22.         ServerSocket u3dServerSocket = null;  
  23.   
  24.         while(true){  
  25.               
  26.             try {  
  27.                   
  28.                 u3dServerSocket=new ServerSocket(8000);  
  29.                   
  30.                 System.out.println("u3d服务已经启动,监听8000端口");  
  31.                   
  32.                 while (true) {  
  33.                     Socket socket = u3dServerSocket.accept();  
  34.                     System.out.println("客户端接入");  
  35.                     new RequestReceiver(socket).start();  
  36.                 }  
  37.                   
  38.                   
  39.             } catch (IOException e) {  
  40.                 System.err.println("服务器接入失败");  
  41.                 if (u3dServerSocket != null) {  
  42.                     try {  
  43.                         u3dServerSocket.close();  
  44.                     } catch (IOException ioe) {  
  45.                     }  
  46.                     u3dServerSocket = null;  
  47.                 }  
  48.             }  
  49.               
  50.             // 服务延时重启  
  51.             try {  
  52.                 Thread.sleep(5000);  
  53.             } catch (InterruptedException e) {  
  54.   
  55.             }  
  56.               
  57.         }  
  58.           
  59.           
  60.     }  
  61.       
  62.       
  63.       
  64.     /** 
  65.      * 客户端请求接收线程 
  66.      * @author lm 
  67.      * 
  68.      */  
  69.     class RequestReceiver extends Thread {  
  70.   
  71.         /** 报文长度字节数 */  
  72.         private int messageLengthBytes = 1024;  
  73.   
  74.         private Socket socket;  
  75.   
  76.         /** socket输入处理流 */  
  77.         private BufferedInputStream bis = null;  
  78.           
  79.   
  80.         public RequestReceiver(Socket socket) {  
  81.             this.socket = socket;  
  82.         }  
  83.   
  84.         @Override  
  85.         public void run() {  
  86.             try {  
  87.                 bis = new BufferedInputStream(socket.getInputStream());  
  88.                 byte[] buf = new byte[messageLengthBytes];  
  89.                   
  90.                 /** 
  91.                  * 在Socket报文传输过程中,应该明确报文的域 
  92.                  */  
  93.                 while (true) {  
  94.               
  95.                     /* 
  96.                      * 这种业务处理方式是根据不同的报文域,开启线程,采用不同的业务逻辑进行处理 
  97.                      * 依据业务需求而定  
  98.                      */  
  99.                     //new RequestHandler(socket, buf).start();   
  100.                     bis.read(buf);  
  101.                     System.out.println(new String(buf,"utf-8"));  
  102.                     Message msg=new GeneralMessage("i am server");  
  103.                     msg.write(socket.getOutputStream());  
  104.                 }  
  105.                   
  106.             } catch (IOException e) {  
  107.                 System.err.println("读取报文出错");  
  108.             } finally {  
  109.                 if (socket != null) {  
  110.                     try {  
  111.                         socket.close();  
  112.                     } catch (IOException e) {  
  113.                     }  
  114.                     socket = null;  
  115.                 }  
  116.             }  
  117.               
  118.         }  
  119.     }  
  120.       
  121.       
  122.     /** 
  123.      * 描述: 请求处理器 
  124.      *  
  125.      */  
  126. /*  class RequestHandler extends Thread { 
  127.  
  128.  
  129.          
  130.  
  131.     } 
  132. */  
  133.   
  134. }  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1.   
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <pre name="code" class="java">public class U3dApplication {  
  2.       
  3.     private static U3dApplication instance = null;  
  4.   
  5.     private boolean stop;  
  6.   
  7.     private U3dApplication() {  
  8.     }  
  9.   
  10.     public static synchronized U3dApplication getApplication() {  
  11.         if (instance == null) {  
  12.             instance = new U3dApplication();  
  13.         }  
  14.         return instance;  
  15.     }  
  16.       
  17.     public void start() {  
  18.         init();  
  19.         new Thread(new U3dServer(), "U3d Server").start();  
  20.   
  21.         while (!stop) {  
  22.             try {  
  23.                 Thread.sleep(1000);  
  24.             } catch (InterruptedException e) {  
  25.             }  
  26.         }  
  27.     }  
  28.       
  29.     /** 
  30.      * @param args 
  31.      */  
  32.     public static void main(String[] args) {  
  33.         Runtime.getRuntime().addShutdownHook(new Thread() {  
  34.             @Override  
  35.             public void run() {  
  36.                 getApplication().stopMe();  
  37.             }  
  38.         });  
  39.         getApplication().start();  
  40.     }  
  41.       
  42.     public void stopMe() {  
  43.         System.out.println("系统即将关闭...");  
  44.     }  
  45.       
  46.       
  47.     /** 
  48.      * 初始化系统 
  49.      */  
  50.     private void init() {  
  51.           
  52.     }  
  53.   
  54. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值