Unity3d基於Socket通信例子(轉)

按語:按照下文,服務端利用網絡測試工具,把下面客戶端代碼放到U3D中攝像機上,運行結果正確。php

http://www.manew.com/thread-102109-1-1.htmlhtml

在一個網站上看到有關於Socket的通信事例,就拿來學習學習,高手就莫噴! 原文連接:http://bbs.9ria.com/thread-364859-1-1.html 首先, 直接兩個服務器端代碼丟到相機上,而後也把客戶端代碼掛到相機上,發佈服務端,再把服務器兩個代碼勾掉再發布客戶端最後運行服務端,再運行客戶端。 unity裏面展現:file:///C:/Users/Administrator/AppData/Local/YNote/data/qq233344ACD512D13C553FF71505B4C730/8d394e1cb202445dafbc1da3c2f90daa/clipboard.png <ignore_js_op>服務器

file:///C:/Users/Administrator/AppData/Local/YNote/data/qq233344ACD512D13C553FF71505B4C730/8d394e1cb202445dafbc1da3c2f90daa/clipboard.png 運行效果: <ignore_js_op>學習

服務端代碼:Progrm.CS

[C#] 純文本查看 複製代碼
?
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using UnityEngine.UI;
using System.Net;
using System.Threading;
  
public class Program : MonoBehaviour
{
     // 設置鏈接端口
     const int portNo = 500;
     // Use this for initialization
     void Start () {
         Thread myThread = new Thread(ListenClientConnect); //開啓協程
         myThread.Start();
     }
     // Update is called once per frame
     void Update () {
}
     private void ListenClientConnect()
     {
         // 初始化服務器IP
         IPAddress localAdd = IPAddress.Parse( "127.0.0.1" );
         // 建立TCP偵聽器
         TcpListener listener = new TcpListener(localAdd, portNo);
         listener.Start();
         // 顯示服務器啓動信息
        // oldstr = String.Concat("正在啓動服務器!");
        // textshow.text = oldstr;
         //("Server is starting...\n");
         // 循環接受客戶端的鏈接請求
         while ( true )
         {
             ChatClient user = new ChatClient(listener.AcceptTcpClient());
             // 顯示鏈接客戶端的IP與端口
             print(user._clientIP + " 加入服務器\n" );
         }
     }
  
}

服務端代碼:ChatClient.CS

[C#] 純文本查看 複製代碼
?
 
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System;
using System.Net;
using System.Threading;
using UnityEngine.UI;
using System.Text;
 
public class ChatClient : MonoBehaviour {
     public static Hashtable ALLClients = new Hashtable(); // 客戶列表
     private TcpClient _client;  // 客戶端實體
     public string _clientIP;   // 客戶端IP
     private string _clientNick; // 客戶端暱稱
     private byte [] data;     // 消息數據
     private bool ReceiveNick = true ;
     public ChatClient(TcpClient client)
     {
         this ._client = client;
         this ._clientIP = client.Client.RemoteEndPoint.ToString();
         // 把當前客戶端實例添加到客戶列表當中
         ALLClients.Add( this ._clientIP, this );
         data = new byte [ this ._client.ReceiveBufferSize];
         // 從服務端獲取消息
         client.GetStream().BeginRead(data, 0, System.Convert.ToInt32( this ._client.ReceiveBufferSize), ReceiveMessage, null );
     }
     // 從客戶端獲取消息
     public void ReceiveMessage(IAsyncResult ar)
     {
         int bytesRead;
         try
         {
             lock ( this ._client.GetStream())
             {
                 bytesRead = this ._client.GetStream().EndRead(ar);
             }
             if (bytesRead < 1)
             {
                 ALLClients.Remove( this ._clientIP);
                 Broadcast( this ._clientNick + " 已經離開服務器" ); //已經離開服務器
                 return ;
             }
             else
             {
                 string messageReceived = Encoding.UTF8.GetString(data, 0, bytesRead);
                 if (ReceiveNick)
                 {
                    this ._clientNick = messageReceived;
                    Broadcast( this ._clientNick + " 已經進入服務器" ); //已經進入服務器
                    //this.sendMessage("hello");
                    ReceiveNick = false ;
                 }
                 else
                 {
                     Broadcast( this ._clientNick + ">>>>" + messageReceived);
                 }
             }
             lock ( this ._client.GetStream())
             {
                 this ._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32( this ._client.ReceiveBufferSize), ReceiveMessage, null );
             }
         }
         catch (Exception ex)
         {
             ALLClients.Remove( this ._clientIP);
             Broadcast( this ._clientNick + " 已經離開服務器" ); //已經離開服務器
         }
     }
 
     // 向客戶端發送消息
     public void sendMessage( string message)
     {
         try
         {
             System.Net.Sockets.NetworkStream ns;
             lock ( this ._client.GetStream())
             {
                 ns = this ._client.GetStream();
             }
             // 對信息進行編碼
             byte [] bytesToSend = Encoding.UTF8.GetBytes(message);
             ns.Write(bytesToSend, 0, bytesToSend.Length);
             ns.Flush();
         }
         catch (Exception ex)
         {
                   Debug.Log( "Error:" +ex);
         }
     }
 
     // 向客戶端廣播消息
     public void Broadcast( string message)
     {
        // oldstr= message+"\n";
         print( message); //打印消息
 
         foreach (DictionaryEntry c in ALLClients)
         {
             ((ChatClient)(c.Value)).sendMessage(message + Environment.NewLine);
         }
     }
     void Update()
     {
     }
}

客戶端代碼:ClientHandler.CS

[C#] 純文本查看 複製代碼
?
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System;
using System.Text;
 
public class ClientHandler : MonoBehaviour {
 
     const int portNo = 500;
     private TcpClient _client;
     private  byte [] data;
 
     public string nickName = "" ;
     public string message = "" ;
     public string sendMsg = "" ;
     // Use this for initialization
     void OnGUI()
     {
         nickName = GUI.TextField( new Rect(10, 10, 100, 20), nickName);
         message = GUI.TextArea( new Rect(10, 40, 300, 200), message);
         sendMsg = GUI.TextField( new Rect(10, 250, 210, 20), sendMsg);
 
         if (GUI.Button( new Rect(120, 10, 80, 20), "Connect" ))
         {
             //Debug.Log("hello");
             this ._client = new TcpClient();
             this ._client.Connect( "127.0.0.1" , portNo);
 
             data = new byte [ this ._client.ReceiveBufferSize];
 
             //SendMyMessage(txtNick.Text);
             SendMyMessage(nickName);
 
             this ._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32( this ._client.ReceiveBufferSize), ReceiveMessage, null );
         };
 
         if (GUI.Button( new Rect(230, 250, 80, 20), "Send" ))
         {
             SendMyMessage(sendMsg);
             sendMsg = "" ;
         };
     }
 
     /// <summary>
     /// 向服務器發送數據(發送聊天信息)
     /// </summary>
     /// <param name="message"></param>
     public void SendMyMessage( string message)
     {
         try
         {
             NetworkStream ns = this ._client.GetStream();
 
             byte [] data = Encoding.UTF8.GetBytes(message);
 
             ns.Write(data, 0, data.Length);
             ns.Flush();
         }
         catch (Exception ex)
         {
             Debug.Log( "Error:" + ex);
         }
     }
     /// <summary>
     /// 接收服務器的數據(聊天信息)
     /// </summary>
     /// <param name="ar"></param>
     public void ReceiveMessage(IAsyncResult ar)
     {
         try
         {
             int bytesRead;
             bytesRead = this ._client.GetStream().EndRead(ar);
 
             if (bytesRead < 1)
             {
                 return ;
             }
             else
             {           
                 message += Encoding.UTF8.GetString(data, 0, bytesRead).ToString();
             }
 
             this ._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32( this ._client.ReceiveBufferSize), ReceiveMessage, null );
         }
         catch (Exception ex)
         {
             print( "Error:" + ex);
         }
     }
     void Start () {
}
// Update is called once per frame
   void Update () {
   }
}

附上小小工程一個,不嫌棄就拿走

本帖隱藏的內容

連接:https://pan.baidu.com/s/1a6lM4HZzkUjqI_YyfNOv4A 密碼:1ije
相關文章
相關標籤/搜索