大概流程:
- 创建套接字
- 绑定套接字到ip和端口
- 侦听连接
- 接收连接
- 与客户端收发数据
- 返回等待另一连接
- 断开连接
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class TCPTest : MonoBehaviour {
private Socket clientSocket;
private Thread mThread;
public void StartUp()
{
try
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect("x.x.x.x", 10000);
mThread = new Thread(AcceptServerMSG);
mThread.Start();
}
catch (System.Exception)
{
throw;
}
}
public void AcceptServerMSG()
{
byte[] buffer = new byte[1024 * 64];
while (true)
{
try
{
int len = clientSocket.Receive(buffer);
string str = Encoding.UTF8.GetString(buffer, 0, len);
Debug.Log("Reveive Msg Form Server: " + str);
}
catch (Exception e)
{
Debug.Log(e.Message);
}
}
}
public void Send(string str)
{
try
{
//将字符串转换为数组;
byte[] strBytes = Encoding.UTF8.GetBytes(str);
clientSocket.Send(strBytes);
}
catch (Exception e)
{
Debug.Log(e.Message);
}
}
public void Close()
{
if (clientSocket.Connected)
{
clientSocket.Close();
}
mThread.Abort();
}
}
由于创建连接后有接收循环,所以要单独开一个线程,否则主线程会卡死。
初始化:
TCPTest client = new Client();
client.StartUp();
发送消息:
client.Send(str);