Unity3d基于Socket通讯例子(转)

按语:按照下文,服务端利用网络测试工具,把下面客户端代码放到U3D中摄像机上,运行结果正确。

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

在一个网站上看到有关于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>

170852ep29d9rlojpje9cd.png (161.87 KB, 下载次数: 79)

下载附件  保存到相册

2017-3-28 13:37 上传

 

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

170912g8jor9up9rbpncgj.png (311.03 KB, 下载次数: 73)

下载附件  保存到相册

2017-3-28 13:37 上传

 

服务端代码: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

转载于:https://www.cnblogs.com/xihong2014/p/11127227.html

  • 0
    点赞
  • 2
    收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值