Python Sever:
import threading
from socket import *
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(8)
def thread_it(func, *args):
'''将函数打包进线程'''
t = threading.Thread(target=func, args=args)
t.setDaemon(False)
t.start()
def acceptSuc(tcpCliSock, addr):
print('有一个客户端连接成功')
while True:
try:
recv_data = tcpCliSock.recv(BUFSIZ)
except ConnectionResetError:
print('有一个客户端关闭了连接')
if recv_data:
data=recv_data.decode('utf-8')
print('接收到%s' % data)
tcpCliSock.send((data+" received").encode())
while True:
print('waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept()
print('...connnecting from:', addr)
thread_it(acceptSuc, tcpCliSock, addr)
print(tcpCliSock)
Unity Client:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class TcpClient : MonoBehaviour
{
public static IPAddress ip;
IPEndPoint ipEnd;
Thread connectThread;
public static Socket serverSocket;
string recvStr; //接收的字符串
string sendStr; //发送的字符串
public static byte[] sendData=new byte[1024];//接收的数据,必须为字节
byte[] recvData=new byte[1024];//发送的数据,必须为字节
int recvLen; //接收的数据长度
string editString="";
void InitSocket()
{
// ip=IPAddress.Parse("x.x.x.x");
ip=IPAddress.Parse("127.0.0.1");
ipEnd=new IPEndPoint(ip,21567);
connectThread=new Thread(new ThreadStart(SocketReceive));
connectThread.Start();
}
void SocketConnet()
{
if(serverSocket!=null)
serverSocket.Close();
serverSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
Debug.Log("Ready to connect.");
serverSocket.Connect(ipEnd);
}
static string? UTF8String( string? input)
{
UTF8Encoding utf8 =? new? UTF8Encoding();
return? utf8.GetString(utf8.GetBytes(input));
}
public static void SocketSend(string sendStr)
{
Debug.Log(sendStr);
TcpClient.sendData=new byte[1024];
TcpClient.sendData=Encoding.ASCII.GetBytes(sendStr);
serverSocket.Send(TcpClient.sendData,TcpClient.sendData.Length,SocketFlags.None);
}
void SocketReceive()
{
SocketConnet();
while(true)
{
recvData=new byte[1024];
recvLen=serverSocket.Receive(recvData);
if(recvLen==0)
{
SocketConnet();
continue;
}
???????? UTF8Encoding utf8 =? new? UTF8Encoding();
recvStr=utf8.GetString(recvData,0,recvLen);
Debug.Log(recvStr);
}
}
void SocketQuit()
{
//关闭线程
if(connectThread!=null)
{
connectThread.Interrupt();
connectThread.Abort();
}
//最后关闭服务器
if(serverSocket!=null)
serverSocket.Close();
print("diconnect");
}
void Start()
{
InitSocket();
}
void OnApplicationQuit()
{
SocketQuit();
}
void OnGUI()
{
int xpos=10;
editString=GUI.TextField(new Rect(xpos,10,500,20),editString);
string split=((char)1).ToString();
if(GUI.Button(new Rect(xpos,30,60,20),"send"))
SocketSend(editString);
}
}
效果:
|