Unity3d使用Socket與java服務器通信

---------------------------客戶端----------------------------------------

[csharp] view plaincopy在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 plaincopy在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 plaincopy在CODE上查看代碼片派生到我的代碼片
  1.   
[java] view plaincopy在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. }  


轉自:http://blog.csdn.net/angelmymei/article/details/40742825

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章