找回密码
 立即注册
查看: 12830|回复: 102

[网络] Unity3d基于Socket通讯例子

  [复制链接]
发表于 2013-8-22 10:47 | 显示全部楼层 |阅读模式
资源信息 Tutorial Information
教程名称: Unity3d基于Socket通讯例子(发帖教程)
适用引擎:   (适用引擎,为空默认为Unity)
教程语种: 中文
教程等级: 1
教程格式: 图文(请用IE9以上浏览器访问本版块)
教程作者: http://bbs.9ria.com/thread-156032-1-1.html (如有问题请短消息联系作者或发表回复)
下载地址: (兑换积分)
点击查看原图
美丽分割线
本人是新手,但是找了很久都找不到类似的通讯源码,后来终于在一个网站上看到有关于Socket的通讯事例,所以就抄过来希望能够帮助更多像我一样的初学者!嘻嘻

首先创建一个C# 控制台应用程序, 直接服务器端代码丢进去,然后再到Unity 里面建立一个工程,把客户端代码挂到相机上,运行服务端,再运行客户端。 高手勿喷!~!

完全源码已经奉上,大家开始研究吧!! 嘎嘎嘎!
服务端代码:Program.cs
[code=csharp]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace SoketDemo
{
    class Program
    {
        // 设置连接端口
        const int portNo = 500;

        static void Main(string[] args)
        {
            // 初始化服务器IP
            System.Net.IPAddress localAdd = System.Net.IPAddress.Parse("127.0.0.1");

            // 创建TCP侦听器
            TcpListener listener = new TcpListener(localAdd, portNo);

            listener.Start();

            // 显示服务器启动信息
            Console.WriteLine("Server is starting...\n");

            // 循环接受客户端的连接请求
            while (true)
            {
                ChatClient user = new ChatClient(listener.AcceptTcpClient());

                // 显示连接客户端的IP与端口
                Console.WriteLine(user._clientIP + " is joined...\n");
            }
        }
    }
}[/code]

服务端代码:ChatClient.cs

[code=csharp]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Net.Sockets;

namespace SoketDemo
{
    class ChatClient
    {
        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 + " has left the chat");

                    return;
                }
                else
                {
                    string messageReceived = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);

                    if (ReceiveNick)
                    {
                        this._clientNick = messageReceived;

                        Broadcast(this._clientNick + " has joined the chat.");

                        //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 + " has left the chat.");
            }
        }

        // 向客戶端发送消息
        public void sendMessage(string message)
        {
            try
            {
                System.Net.Sockets.NetworkStream ns;

                lock (this._client.GetStream())
                {
                    ns = this._client.GetStream();
                }

                // 对信息进行编码
                byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);

                ns.Write(bytesToSend, 0, bytesToSend.Length);
                ns.Flush();
            }
            catch (Exception ex)
            {

            }
        }

        // 向客户端广播消息
        public void Broadcast(string message)
        {
            Console.WriteLine(message);

            foreach (DictionaryEntry c in ALLClients)
            {
                ((ChatClient)(c.Value)).sendMessage(message + Environment.NewLine);
            }
        }

    }
}[/code]


客户端代码 :ClientHandler

[code=csharp]using UnityEngine;
using System.Collections;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Net.Sockets;

public class ClientHandler : MonoBehaviour
{
    const int portNo = 500;
    private TcpClient _client;
    byte[] data;

    public string nickName = "";
    public string message = "";
    public string sendMsg = "";

    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];

            //SendMessage(txtNick.Text);
            SendMessage(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"))
        {
            SendMessage(sendMsg);
            sendMsg = "";
        };
    }

    public void SendMessage(string message)
    {
        try
        {
            NetworkStream ns = this._client.GetStream();

            byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

            ns.Write(data, 0, data.Length);
            ns.Flush();
        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.ToString());
        }
    }

    public void ReceiveMessage(IAsyncResult ar)
    {
        try
        {
            int bytesRead;

            bytesRead = this._client.GetStream().EndRead(ar);

            if (bytesRead < 1)
            {
                return;
            }
            else
            {

                Debug.Log(System.Text.Encoding.ASCII.GetString(data, 0, bytesRead));

                message += System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
            }

            this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);


        }
        catch (Exception ex)
        {

        }
    }
}[/code]

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×

评分

参与人数 2 +2 收起 理由
yugo215 + 1 神马都是浮云
graywolfx21 + 1 赞一个!

查看全部评分

发表于 2013-8-23 08:52 | 显示全部楼层
不錯~謝謝分享{:soso_e100:}
发表于 2013-8-23 09:50 | 显示全部楼层
目前用不着,先收着了,谢楼主分享
发表于 2013-8-23 16:20 | 显示全部楼层
“首先创建一个C# 控制台应用程序, ”
这个是什么意思,怎么建?
发表于 2013-8-24 13:06 | 显示全部楼层

感谢楼主的无私分享!{:soso__11402694654016840197_7:}
发表于 2013-8-24 14:41 | 显示全部楼层
“首先创建一个C# 控制台应用程序, ”
这个是什么意思,怎么建?

点评

我这是基于C# Vs实现的, 如果你是学习java的话, 那代码用java控制台程序编写应该也可以,语法有所变动,思维还是不会变的。 第一次学习程序时, 输出 Hello word! 的地方叫控制台,谢谢!  详情 回复 发表于 2013-8-26 14:12
发表于 2013-8-24 18:29 | 显示全部楼层
哟呼呼  想要啊 呵呵
 楼主| 发表于 2013-8-26 14:12 | 显示全部楼层
cclove 发表于 2013-8-24 14:41
“首先创建一个C# 控制台应用程序, ”
这个是什么意思,怎么建?

我这是基于C# Vs实现的, 如果你是学习java的话, 那代码用java控制台程序编写应该也可以,语法有所变动,思维还是不会变的。 第一次学习程序时, 输出 Hello word! 的地方叫控制台,谢谢!
发表于 2013-9-4 09:59 | 显示全部楼层

不错 不错 不错{:soso__3922851084632044791_6:}
发表于 2013-11-12 11:36 | 显示全部楼层
先回复再研究,谢谢了
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-3-29 22:50 , Processed in 0.114885 second(s), 33 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表