首先創建一個C# 控制台應用程式, 直接伺服器端代碼丟進去,然後再到Unity 裡面建立一個工程,把客戶端代碼掛到相機上,運行服務端,再運行客戶端。 高手勿噴!~! 完全源碼已經奉上,大家開始研究吧!! 嘎嘎嘎! 服務端代碼:Program.cs using System; using System ...
首先創建一個C# 控制台應用程式, 直接伺服器端代碼丟進去,然後再到Unity 裡面建立一個工程,把客戶端代碼掛到相機上,運行服務端,再運行客戶端。 高手勿噴!~!
完全源碼已經奉上,大家開始研究吧!! 嘎嘎嘎!
服務端代碼:Program.cs
- 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");
- }
- }
- }
- }
服務端代碼:ChatClient.cs
- 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);
- }
- }
- }
- }
客戶端代碼 :ClientHandler
- 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)
- {
- }
- }
- }
原 帖 地址 http://www.u3dchina.com/forum.php?mod=viewthread&tid=4741&extra=page%3D1%26filter%3Dsortid%26sortid%3D14%26sortid%3D14
如有版權問題 請聯繫我:[email protected]