【Unity 3 D独学記録】Unity 3 DネットワークのSocketチャットルーム初探査

6701 ワード

まず、サービス側のプログラムを作成します.このプログラムは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(" ...
"); // while (true) { ChatClient client = new ChatClient(listener.AcceptTcpClient()); // IP port Console.WriteLine(client._clientIP + " �...
"); } } } }
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)
        {

        }
    }
}

これで~サービス側を開き、クライアントで接続することができます.
ここで使用するコードはASCIIです.仮に中国語を使いたい場合はUTF-8、またはGB 2312に変更します.