客戶端unity腳本
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
public class UIManager : MonoBehaviour {
private string ipaddress = "192.168.3.35";
private int port = 7788;
private Thread t; //創建一個線程方便管理
private byte[] data = new byte[1024];
private string message = "";//Text用來接收Message的容器
public Text text; //聊天框
public InputField textInput; //輸入框
private Socket clientSocket;
// Use this for initialization
void Start () {
ConnectedToServer();
}
// Update is called once per frame
void Update () {
if (message!=null&&message!="")
{
text.text += "\n" + message;
message = "";//清空消息
}
}
//和服務器連接的方法
private void ConnectedToServer()
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//發起連接
clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipaddress), port));
//創建一個線程用來接收消息
t = new Thread(ReceiveMeage);
t.Start();
}
/// <summary>
/// 用來循環接收消息
/// </summary>
void ReceiveMeage()
{
while (true)
{
//判斷是否和服務器連接
if (clientSocket.Connected==false)
{
break;
}
int length = clientSocket.Receive(data);
message = Encoding.UTF8.GetString(data, 0, length);
//text.text += "\n" + message; //unity不允許單獨的線程操縱unity組件
}
}
//UI界面發送按鈕的方法
public void SendMessage(string message)
{
//字符串轉成字節數組
byte[] data = Encoding.UTF8.GetBytes(message);
clientSocket.Send(data); //發送到服務器端
}
//當按鈕點擊的時候獲取文本框內的信息
public void OnSendButtonClick()
{
string value = textInput.text; //得到文本框內的內容
SendMessage(value);
//發送完輸入框爲空
textInput.text = "";
}
//防止客戶端斷開連接服務器一直接收消息
private void OnDestroy()
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();//關閉連接
}
}
服務器端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using 聊天室服務器端_tcp;
namespace 聊天室服務器端
{
/// <summary>
/// 用來跟客戶端做通信
/// </summary>
class Client
{
private Socket clientSocket;
private Thread t; //方便管理線程
private byte[] data = new byte[1024];//數據容器,方便頻繁調用
public Client(Socket s)
{
clientSocket = s;
//啓動一個線程 處理客戶端的數據接收
t = new Thread(ReceiveMessage);
t.Start();
}
private void ReceiveMessage()
{
//一直接收客戶端的數據
while (true)
{
//在接收數據之前,判斷一下Socket是否斷開
if (clientSocket.Poll(10, SelectMode.SelectRead))//判斷客戶端是否斷開連接
{
clientSocket.Close();
break;//跳出循環 終止線程
}
//當客戶端斷開連接時會一直接收消息,所以要在客戶端做處理
int length = clientSocket.Receive(data);
string message = Encoding.UTF8.GetString(data, 0, length);
//服務器接收到數據,要把這個數據分發到客戶端
//廣播這個消息
Program.BroadCastMessage(message);
Console.WriteLine("收到了消息" + message);
}
}
//--------------向多個客戶端發送消息------------------------
/// <summary>
/// 發送方法
/// </summary>
/// <param name="message"></param>
public void SendMessage(string message)
{
byte[] data = Encoding.UTF8.GetBytes(message);
clientSocket.Send(data);
}
/// <summary>
/// 判斷是否和客戶端斷開連接
/// </summary>
public bool Connected
{
get { return clientSocket.Connected; }//返回這個Socket是否斷開連接
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using 聊天室服務器端;
/// <summary>
/// 服務器端
/// </summary>
namespace 聊天室服務器端_tcp
{
class Program
{
//創建一個空的集合存放連接過來的client對象,就可以知道服務器和哪些客戶端建立了連接
static List<Client> clientList = new List<Client>();
/// <summary>
/// 廣播消息分發到各個客戶端
/// </summary>
public static void BroadCastMessage(string message)
{
var notConnectedList = new List<Client>();//存放斷開連接的客戶端
foreach (var client in clientList)
{
if(client.Connected) //客戶端在連接狀態
client.SendMessage(message);
else
{
//斷開連接的客戶端放到這個集合
notConnectedList.Add(client);
}
}
//把斷開連接的客戶端從clientList中移除掉
foreach (var temp in notConnectedList)
{
clientList.Remove(temp);//移除
}
}
static void Main(string[] args)
{
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
tcpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.3.35"),7788));
tcpServer.Listen(100);
Console.WriteLine("服務器連接成功");
//--------------接收多個連接---------------
while (true)
{
Socket clientSocket = tcpServer.Accept();
Console.WriteLine("一個客戶端連接過來");
Client client = new Client(clientSocket);//把收發消息的邏輯放到Client類裏處理
clientList.Add(client);
}
}
}
}