欢迎加入Unity业内qq交流群:956187480



服务器

public class TcpServer : MonoBehaviour {
public Button button;
Thread serverThread;
Socket serverSocket;
// Use this for initialization
void Start ()
{
button.onClick.AddListener(StartSever);
}

private void StartSever()
{
//定义侦听端口
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 8889);
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(ipEnd);
serverSocket.Listen(10);
Debug.Log("等待连接。。。");
serverThread = new Thread(ServerThread);
serverThread.Start();
}

private void ServerThread()
{
//一旦接受连接,创建一个客户端
Socket client = serverSocket.Accept();
IPEndPoint ipEndClient = (IPEndPoint)client.RemoteEndPoint;
Debug.Log("已连接" + ipEndClient.Address + ipEndClient.Port);
while (true)
{
Thread.Sleep(100);
//接收数据
byte[] recv1 = new byte[1024];
if (client.Available <= 0) continue;
int count1 = client.Receive(recv1);
Debug.Log("客户端:"+Encoding.UTF8.GetString(recv1, 0, count1));

//发送数据
string welcome = "我是服务器" ;
byte[] data = new byte[1024];
data = Encoding.UTF8.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);
}
}

private void OnDestroy()
{
if (serverThread != null)
{
serverThread.Abort();
}
if (serverSocket!=null)
{
serverSocket.Close();
serverSocket = null;
}
}
}

客户端

public class TcpClient : MonoBehaviour {
public Button client;
Socket clientSocket;
Thread clientThread;

// Use this for initialization
void Start () {
client.onClick.AddListener(StartClient);
}

private void StartClient()
{
//服务器地址
IPAddress ip = IPAddress.Parse("192.168.10.99");
IPEndPoint ipEnd = new IPEndPoint(ip, 8889);
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(ipEnd);
clientThread = new Thread(ClientThread);
clientThread.Start();
}

private void ClientThread()
{
while (true)
{
Thread.Sleep(100);
//发送数据
string msg = "哈喽,我是客户端";
byte[] msgBytes = new byte[1024];
msgBytes = Encoding.UTF8.GetBytes(msg);
clientSocket.Send(msgBytes, msgBytes.Length, SocketFlags.None);

//接收数据
byte[] recvMsg = new byte[1024];
if (clientSocket.Available <= 0) continue;
int count = clientSocket.Receive(recvMsg);
Debug.Log("服务器:" + Encoding.UTF8.GetString(recvMsg, 0, count));
}
}

private void OnDestroy()
{
if (clientSocket!=null)
{
clientSocket.Close();
clientSocket = null;
}
if (clientThread!=null)
{
clientThread.Abort();
}
}
}

欢迎加入Unity业内qq交流群:956187480