TCP客户端
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;public class TCPClient
{/// <summary>/// 客户端/// </summary>private TcpClient tcpClient;private NetworkStream stream;public TCPClient(string ip, int port){try{//初始化客户端tcpClient = new TcpClient(ip, port); // 连接到指定的服务器地址和端口stream = tcpClient.GetStream();// 开始接收数据byte[] buffer = new byte[1024];stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(ReceiveCallback), buffer);}catch (Exception e){Debug.Log("错误Error: " + e.Message);}}/// <summary>/// 发送消息/// </summary>/// <param name="message"></param>public void Send(string message){if (stream == null){Debug.Log("Error: TCP connection is not established.");return;}byte[] data = System.Text.Encoding.UTF8.GetBytes(message);stream.Write(data, 0, data.Length);Debug.Log("Sent message: " + message);}int a;private void Update(){if (Input.GetKeyDown(KeyCode.Space)){Send("我是小偷" + a++);}}/// <summary>/// 接收消息/// </summary>/// <param name="ar"></param>private void ReceiveCallback(IAsyncResult ar){int bytesRead = stream.EndRead(ar);if (bytesRead == 0){return;}byte[] data = (byte[])ar.AsyncState;string message = System.Text.Encoding.UTF8.GetString(data, 0, bytesRead);Debug.Log("收到消息Received message: " + message);// 继续监听下一条消息stream.BeginRead(data, 0, data.Length, new AsyncCallback(ReceiveCallback), data);}public void SocketQuit(){if (tcpClient != null){tcpClient.Close();}}
}
TCP服务器
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;public class TCPServer
{/// <summary>/// 客户端/// </summary>private Socket socketClient;/// <summary>/// 服务器/// </summary>private Socket socketServer;/// <summary>/// 监听线程/// </summary>private Thread thread;private Thread r_thread;/// <summary>/// 开启服务器监听/// </summary>/// <param name="ip">ip</param>/// <param name="port">端口</param>public TCPServer(string ip, int port){socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);IPAddress iPAddress = IPAddress.Parse(ip);EndPoint endPoint = new IPEndPoint(iPAddress, port);socketServer.Bind(endPoint);socketServer.Listen(5);//监听连接thread = new Thread(ReceiveFromClient);thread.IsBackground = true;thread.Start(socketServer);}/// <summary>/// 监听连接的客户端/// </summary>/// <param name="obj"></param>private void ReceiveFromClient(object obj){try{Socket socketWatch = obj as Socket;while (true){socketClient = socketWatch.Accept();r_thread = new Thread(ReceiveMsg);r_thread.IsBackground = true;r_thread.Start(socketClient);}}catch (System.Exception e){Debug.Log(e.Message);}}/// <summary>/// 接收数据/// </summary>/// <param name="obj"></param>public void ReceiveMsg(object obj){Socket socket = obj as Socket;while (true){byte[] buffer = new byte[1024];int length = socket.Receive(buffer);if (length == 0){return;}byte[] dataCache = new byte[length];for (int i = 0; i < length; i++){//存储数据dataCache[i] = buffer[i];}string message = System.Text.Encoding.UTF8.GetString(dataCache);Debug.Log("收到消息Received message: " + message);}}public void Send(string sendStr){//清空发送缓存byte[] sendData = new byte[1024];//数据类型转换sendData = Encoding.UTF8.GetBytes(sendStr);//发送socketClient.Send(sendData, sendData.Length, SocketFlags.None);Debug.Log("Sent message: " + sendStr);}/// <summary>/// 关闭/// </summary>public void SocketQuit(){if (socketClient != null){socketClient.Close();}if (thread != null){thread.Interrupt();thread.Abort();}if (r_thread != null){r_thread.Interrupt();r_thread.Abort();}if (socketServer != null){socketServer.Close();}Debug.Log("关闭服务器");}
}