找到的可实际使用的unity-python socket双工通信代码

互联网啥都能找到, 但是好的东西却往往如同大海捞针.

找个可实现的socket双工通信代码实现, 由于基础了解也比较薄弱, 废了老大劲才翻到了两个可实际使用的代码. 这里做下归纳整理
实现时需要先启动server端, 再启动client端

Python server端

来源于https://www.cnblogs.com/crazyechoaoo/p/10571656.html
这里只摘抄和改造了server端, 原文中也有client端的实现

我自己的这个demo只需要pip install loguru, 一个日志模块即可使用
不想用loguru的logger, 将logger.info和logger.debug换成print()也行

环境是python3.9

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import socket  
import threading  
import time  
import random  
  
from loguru import logger  
  
  
def main():  
    s = socket.socket()  # 创建 socket 对象  
    # host = socket.gethostname()  # 获取本地主机名  
    host = "127.0.0.1"  
  
    logger.info('host name=' + str(host))  
    port = 7788  # 设置端口  
    s.bind((host, port))  # 绑定端口  
  
    s.listen(5)  # 等待客户端连接  
    logger.info("server start...")  
    c, addr = s.accept()  # 建立客户端连接  
    logger.info('连接地址:' + str(addr))  
    return c  
  
  
def send_message(c: socket):  
    while True:  
        time.sleep(random.randint(1, 5))  
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())  
        c.send(('server test, time=' + timestamp).encode("utf-8"))  
        logger.debug("server send finish time=" + timestamp)  
  
  
def receive_message(c: socket):  
    while True:  
        recv_data = c.recv(1024)  
        if recv_data and len(recv_data) > 0:  
            logger.info(f"receive client message: " + recv_data.decode("utf-8"))  
  
  
if __name__ == "__main__":  
    c = None  
    try:  
        c = main()  
        t_send = threading.Thread(target=send_message, args=(c,))  
        t_receive = threading.Thread(target=receive_message, args=(c,))  
        t_send.start()  
        t_receive.start()  
    except KeyboardInterrupt:  
        if c and type(c) == socket:  
            c.close()  
  

Unity client端

来源于http://www.codebaoku.com/it-csharp/it-csharp-229369.html
将这个代码挂载到一个GameObject中即可.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;  
using System.Collections;  
using System.Net;  
using System.Net.Sockets;  
using System.Text;  
using System.Threading;  
using UnityEngine;  
  
public class SocketManager : MonoBehaviour  
{  
      
    public string ipAddress = "127.0.0.1";  
    public int port = 7788;  
  
    private Socket clientSocket;  
      
    byte[] _data = new byte[1024];  
  
    private Thread _thread;  
    private string _message;  
  
    private void Start()  
    {  
        ConnectToServer();  
    }  
  
    void ConnectToServer()  
    {  
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
        clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipAddress), port));  
  
        _thread = new Thread(ReceiveMessage);  
        _thread.Start();  
        StartCoroutine(RandomSend());  
    }  
  
    // 启动线程, 持续接收消息  
    void ReceiveMessage()  
    {  
        while (true)  
        {  
            if (clientSocket.Connected == false)  
                break;  
            int length = clientSocket.Receive(_data);  
  
            _message = Encoding.UTF8.GetString(_data, 0, length);  
              
            Debug.Log("receive message: " + _message);  
        }  
    }  
  
  
    // 使用IEnumerator, 每隔2秒发送给server端一次消息  
    IEnumerator RandomSend()  
    {  
        while (true)  
        {  
            SendMessages("client send..." + DateTime.Now);  
            yield return new WaitForSeconds(2f);  
        }  
    }  
  
    void SendMessages(string message)  
    {  
        byte[] data = Encoding.UTF8.GetBytes(message);  
        clientSocket.Send(data);  
    }  
  
    void OnDestroy()  
    {  
        _thread.Abort();  
        clientSocket.Shutdown(SocketShutdown.Both);  //既不接受也不发送  
        clientSocket.Close();  //关闭连接  
    }  
}