TCP相关API介绍与服务端编写
创建两个类TcpService.cs与Client.cs
TcpService.cs 用于启动TCP服务以及监听功能
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Service.Net
{
internal class TCPService
{
TcpListener tcpListener;
/// <summary>
/// 启动服务端
/// </summary>
public void Start()
{
}
/// <summary>
/// 监听客户端的链接
/// </summary>
public async void Accpet()
{
}
}
}
Client.cs 用于缓存客端端链接以及消息的接收与发送
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Service.Net
{
internal class Client
{
TcpClient client;
public Client(TcpClient tcpClient)
{
client = tcpClient;
}
/// <summary>
/// 接受消息
/// </summary>
public async void Receive()
{
}
/// <summary>
/// 发送消息
/// </summary>
public async void Send(byte[] data)
{
}
}
}
实现TcpService.cs与Client.cs中的方法
TcpService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Service.Net
{
internal class TCPService
{
TcpListener tcpListener;
/// <summary>
/// 启动服务端
/// </summary>
public void Start()
{
try
{
//创建监听器
tcpListener = TcpListener.Create(7788);//端口范围1-65535
tcpListener.Start(500);//允许接收多少客户端链接
Console.WriteLine("Tcp Service Start!!!");
Accpet();//开始监听
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
/// <summary>
/// 监听客户端的链接
/// </summary>
public async void Accpet()
{
try
{
TcpClient tcpClient = await tcpListener.AcceptTcpClientAsync();
Console.WriteLine("客户端已连接:" + tcpClient.Client.RemoteEndPoint);//打印链接的客户端IP
Client client = new Client(tcpClient);
Accpet();
}
catch (Exception e)
{
tcpListener.Stop();//停止监听客户端链接
Console.WriteLine($"Accpet:{e.Message}");
}
}
}
}
Client.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Service.Net
{
internal class Client
{
TcpClient client;
public Client(TcpClient tcpClient)
{
client = tcpClient;
Receive();
}
/// <summary>
/// 接受消息
/// </summary>
public async void Receive()
{
try
{
while (client.Connected)
{
byte[] buffer = new byte[4096];
int length = await client.GetStream().ReadAsync(buffer, 0, buffer.Length);
if (length > 0)
{
Console.Write($"接收到的数据长度:{length}--------");
Console.WriteLine($"接收到的数据长度:{Encoding.UTF8.GetString(buffer, 0, length)}");
}
else
{
//客户端关闭了
client.Close();
Console.WriteLine($"客户机{client.Client.RemoteEndPoint}断开连接");
}
}
}
catch(Exception e)
{
Console.WriteLine($"Receive Error:{e.Message}");
client.Close();
}
}
/// <summary>
/// 发送消息
/// </summary>
public async void Send(byte[] data)
{
try
{
await client.GetStream().WriteAsync(data, 0, data.Length);
Console.WriteLine("数据发送成功");
}
catch(Exception e)
{
client.Close();
Console.WriteLine($"Send Error:{e.Message}");
}
}
}
}
编写启动脚本
using Service.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service
{
internal class Program
{
static void Main(string[] args)
{
TCPService tcpService = new TCPService();
tcpService.Start();
Console.ReadLine();
}
}
}
实现客户端和服务器的消息收发
创建一个unity工程
新建脚本目录以及创建两个脚本
GameManager.cs与Clinet.cs
Clinet.cs
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;
using System;
using System.Net;
using System.Text;
public class Client
{
static Client instance = new Client();
public static Client Instance => instance;
TcpClient client;
//与服务端连接
public void Start()
{
}
//连接服务器
public async void Connect()
{
}
//接收数据
public async void Receive()
{
}
//发送数据
public async void Send(byte[] data)
{
}
}
GameManager.cs
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
public class GameManager : MonoBehaviour
{
void Start()
{
Client.Instance.Start();//开始连接服务器
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))//按键发送数据给服务器
{
string str = "1234567890";//发送的数据内容
byte[] data = Encoding.UTF8.GetBytes(str);//数据转换
Client.Instance.Send(data);//发送数据
}
}
}
实现客户端Client方法
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;
using System;
using System.Net;
using System.Text;
public class Client
{
static Client instance = new Client();
public static Client Instance => instance;
TcpClient client;
public void Start()
{
client = new TcpClient();
Connect();
}
public void CloseConnect()
{
if(client.Connected)
client.Close();
}
//连接服务器
public async void Connect()
{
try
{
//通过使用IPAddress.Parse方法,可以将字符串表示的IP地址转换为IPAddress对象/
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 7788;
await client.ConnectAsync( ip,port);
Debug.Log("TCP 连接成功!!!");
Receive();
}
catch(Exception e)
{
Debug.Log(e.Message);
}
}
//接收数据
public async void Receive()
{
try
{
while (client.Connected)
{
byte[] buffer = new byte[4096];
int length = await client.GetStream().ReadAsync(buffer, 0, buffer.Length);
if (length > 0)
{
Debug.Log(Encoding.UTF8.GetString(buffer,0,length));
Debug.Log($"接收到的数据了长度为:{length}");
}
else
{
client.Close();
}
}
}
catch (Exception e)
{
client.Close();
Debug.Log(e.Message);
}
}
//发送数据
public async void Send(byte[] data)
{
try
{
await client.GetStream().WriteAsync(data,0,data.Length);
Debug.Log("数据发送成功!!!");
}
catch (Exception e)
{
client.Close();
Debug.Log(e.Message);
}
}
}
服务端数据发送
修改Receive()方法
接收到数据之后返回数据
Send(Encoding.UTF8.GetBytes("服务端数据:09876543210"));
public async void Receive()
{
try
{
while (client.Connected)
{
byte[] buffer = new byte[4096];
int length = await client.GetStream().ReadAsync(buffer, 0, buffer.Length);
if (length > 0)
{
Console.Write($"接收到的数据长度:{length}--------");
Console.WriteLine($"接收到的数据长度:{Encoding.UTF8.GetString(buffer, 0, length)}");
//收到数据之后,向客户端返回数据
Send(Encoding.UTF8.GetBytes("服务端数据:09876543210"));
}
else
{
//客户端关闭了
client.Close();
Console.WriteLine($"客户机{client.Client.RemoteEndPoint}断开连接");
}
}
}
catch(Exception e)
{
Console.WriteLine($"Receive Error:{e.Message}");
client.Close();
}
}