客户端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);
}
}
}
}