【Unity3D自学记录】Unity3D网络之Socket聊天室初探

首先创建一个服务端程序,这个程序就用VS的控制台程序做即可了。

代码例如以下:

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

namespace SocketServer
{
    class Program
    {
        const int Port = 20000; //设置连接port
        static void Main(string[] args)
        {
            // 初始化serverIP
            System.Net.IPAddress SocketIP = System.Net.IPAddress.Parse("127.0.0.1");
            // 创建TCP侦听器
            TcpListener listener = new TcpListener(SocketIP, Port);
            listener.Start();
            // 显示server启动信息
            Console.WriteLine("服务开启中...\n");
            // 循环接受客户端的连接请求
            while (true)
            {
                ChatClient client = new ChatClient(listener.AcceptTcpClient());

                // 显示连接客户端的IP与port
                Console.WriteLine(client._clientIP + " 添?...\n");
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Net.Sockets;

namespace SocketServer
{
    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 + "离开聊天室");
                    return;
                }
                else
                {
                    string messageReceived = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);

                    if (ReceiveNick)
                    {
                        this._clientNick = messageReceived;
                        Broadcast(this._clientNick + "加入聊天室");
                        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 = 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);
            }
        }

    }
}

这个比較简单啊,我就直接拷贝了别人的代码,比較好理解,适合新手~~~(如有侵犯版权,请私信联系我)

接下来就是Unity这边的代码了~

代码例如以下:

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

public class ScoketClient : MonoBehaviour
{
    const int Port = 20000;//port号与服务端port相应
    private TcpClient client;
    byte[] data;

    public string UserName = "";//username
    public string message = "";//聊天内容
    public string sendMsg = "";//输入框

    void OnGUI()
    {
        UserName = GUI.TextField(new Rect(10, 10, 100, 20), UserName);
        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), "连接server"))
        {
            this.client = new TcpClient();
            this.client.Connect("127.0.0.1", Port);
            data = new byte[this.client.ReceiveBufferSize];
            SendSocket(UserName);
            this.client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this.client.ReceiveBufferSize), ReceiveMessage, null);
        };

        if (GUI.Button(new Rect(230, 250, 80, 20), "发送"))
        {
            SendSocket(sendMsg);
            sendMsg = "";
        };
    }

    public void SendSocket(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)
        {

        }
    }

    public void ReceiveMessage(IAsyncResult ar)
    {
        try
        {
            int bytesRead;
            bytesRead = this.client.GetStream().EndRead(ar);
            if (bytesRead < 1)
            {
                return;
            }
            else
            {
                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)
        {

        }
    }
}

这样就能够了~先开启服务端,然后在用client连接。

这里用的编码是ASCII。假设想用中文的话改成UTF-8,或者GB2312。

时间: 2024-08-15 07:57:04

【Unity3D自学记录】Unity3D网络之Socket聊天室初探的相关文章

【Unity3D自学记录】网络编程之TCP&amp;UDP的区别

TCP(Transmission Control Protocol,传输控制协议)是基于连接的协议,也就是说,在正式收发数据前,必须和对方建立可靠的连接.一个TCP连接必须要经过三次"对话"才能建立起来,其中的过程非常复杂,我们这里只做简单.形象的介绍,你只要做到能够理解这个过程即可.我们来看看这三次对话的简单过程:主机A向主机B发出连接请求数据包:"我想给你发数据,可以吗?",这是第一次对话:主机B向主机A发送同意连接和要求同步(同步就是两台主机一个在发送,一个在

【Unity3D自学记录】Unity3D显示NPC名称

using UnityEngine; using System.Collections; public class NPCName : MonoBehaviour { //主角对象 private GameObject player; //主摄像机对象 private Camera camera; //NPC名称 private string name = "我是NPC"; void Start() { //根据Tag得到主角对象 player = GameObject.FindGam

Web Socket 聊天室

Web sockets test Web Socket 聊天室 按下连接按钮,会通过WebSocket发起一个到聊天浏览器的连接. 服务器地址: 用户名: 连接 发送 来自网上.............

python socket 聊天室

import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #绑定端口 s.bind(("127.0.0.1", 8888)) while True: data = s.recvfrom(1024) print(str(data[0].decode("gbk"))) send_data = input("请输入聊天内容") if "exit" in se

Java网络编程案例---聊天室

网络编程是指编写运行在多个设备(计算机)的程序,这些设备都通过网络连接起来. java.net包中JavaSE的API包含有类和接口,它们提供低层次的通信细节.你可以直接使用这些类和接口,来专注于解决问题,而不用关注通信细节. java.net包中提供了两种常见的网络协议的支持: TCP:TCP是传输控制协议的缩写,它保障了两个应用程序之间的可靠通信.通常用于互联网协议,被称TCP/IP. UDP:UDP是用户数据报协议的缩写,一个无连接的协议.提供了应用程序之间要发送的数据的数据报. 本案例以

socket聊天室

1 #服务端 2 from socket import * 3 import json 4 def recvMsg(s): 5 while True: 6 #接收用户的信息 7 data,address = s.recvfrom(1024) 8 data = json.loads(data) 9 print(data,address) 10 11 if data['type'] == 'enter': 12 # 将用户进入聊天室的信息发给其它所有在线用户 13 sendToAll(('>>系统

【Unity3D自学记录】Unity3D之Url地址重定向(C#)

private string url; // Use this for initialization void Start () { HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create("这里填写Url"); myHttpWebRequest.AllowAutoRedirect = false; HttpWebResponse myHttpWebResponse = (HttpWebRespon

【Unity3D自学记录】可视化对照十多种排序算法(C#版)

在这篇文章中.我会向大家展示一些排序算法的可视化过程.我还写了一个工具.大家可对照查看某两种排序算法. 下载源代码 – 75.7 KB 下载演示样例 – 27.1 KB 引言 首先,我觉得是最重要的是要理解什么是"排序算法".依据维基百科.排序算法(Sorting algorithm)是一种能将一串数据按照特定排序方式进行排列的一种算法. 最经常使用到的排序方式是数值顺序以及字典顺序.有效的排序算法在一些算法(比如搜索算法与合并算法)中是重要的,如此这些算法才干得到正确解答.排序算法也

转载 ---- 【Unity3D自学记录】代码获取隐藏游戏对象

http://blog.csdn.net/daijinghui512/article/details/34095553 很多人把游戏物体的active改成false后,用GameObject.Find()就找不到游戏对象了. 我来告诉大家一个巧妙的方法,借鉴的是雨松大神的方法~ 首先创建一个父级OBJ,OBJ的active不能为false 然后将我们隐藏的游戏物体放在OBJ下~ 如图: 代码如下: [csharp] view plain copy <span style="white-sp