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("关闭服务器");
}
}
文章来源地址https://www.toymoban.com/news/detail-818512.html
文章来源:https://www.toymoban.com/news/detail-818512.html
到了这里,关于TCP传输数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!