Unity简单多人聊天室

用unity实现网络通信有很多种方法,比较大型的项目都是自定义通信协议,本文介绍unity自己封装的NetWork通信,一个简单的多人聊天室。

实验环境:unity5.2+VS2015+Win8

具体步骤:

1.启动unity新建工程,并创建脚本Server.cs 挂在一个空物体上,并且添加组件NetworkView。

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Server : MonoBehaviour
{

    private int port = 2000;
    private int connectPort = 32;
    public Text textMsg;
    public Text connetcMsg;

    void Start()
    {
        //创建服务器
        NetworkConnectionError error = Network.InitializeServer(connectPort, port, false);
        if (error == NetworkConnectionError.NoError)
        {
            connetcMsg.text = "服务器创建成功";
        }
        else
        {
            connetcMsg.text = error.ToString();
        }
    }

   
    void Update()
    {
        for (int i = 0; i < Network.connections.Length; i++)
        {

            connetcMsg.text= Network.connections[i].ipAddress + "已连接!";
        }
    }
   //当玩家断开时,清理断开玩家的遗留信息
    void OnPlayerDisconnected(NetworkPlayer player)
    {
        connetcMsg.text = player.ipAddress + "断开连接!";
        Network.RemoveRPCs(player);
        Network.DestroyPlayerObjects(player);
    }

    //接收客户端的消息
    [RPC]
    void ReceiveMessage(string msg, NetworkMessageInfo info)
    {
        textMsg.text = info.sender.ipAddress + "玩家:" + msg;
    }
   

}


2.创建新场景,并创建脚本Client.cs挂在一个空物体上,并且添加NetworkView。

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Client : MonoBehaviour
{

    public Text textMsg;
    public InputField inputMsg;
    private string ip = "127.0.0.1";
    private int port = 2000;

    void Start()
    {
        //客户端连接服务器
        NetworkConnectionError error = Network.Connect(ip, port);
        if (error == NetworkConnectionError.NoError)
        {
            textMsg.text = "连接成功";
        }
        else
        {
            textMsg.text = error.ToString();
        }
    }

    //客户端向服务器或者其他客户端发送消息
    public void SelfSendMessage()
    {
        this.GetComponent<NetworkView>().RPC("ReceiveMessage", RPCMode.Others, inputMsg.text);
        inputMsg.text = "";
    }
    
    //接收其他客户端的消息
    [RPC]
    void ReceiveMessage(string msg, NetworkMessageInfo info)
    {
        textMsg.text = info.sender.ipAddress + "玩家:" + msg;
    }
}


3.Build 1个服务端程序和2个客户端程序,并注意勾选后台运行。


4.运行效果图。



转载请注明出处:http://blog.csdn.net/gzw187327
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值