python之socket编程

Posted raindi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之socket编程相关的知识,希望对你有一定的参考价值。

单用户连接:
socket_client.py

import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((\'127.0.0.1\', 8000))
while True:
    re_data = input()
    client.send(re_data.encode(\'utf8\'))
    data = client.recv(1024)
    print(data.decode(\'utf8\'))
socket_server.py

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((\'0.0.0.0\', 8000))
server.listen()
sock,addr = server.accept()
while True:
    data = sock.recv(1024)
    print(data.decode(\'utf8\'))
    re_data = input()
    sock.send(re_data.encode(\'utf8\'))
多用户连接(利用多线程)
socket_server.py

import socket, threading

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((\'0.0.0.0\', 8000))
server.listen()

def handle_sock(sock, addr):
    data = sock.recv(1024)
    print(data.decode(\'utf8\'))
    re_data = input()
    sock.send(re_data.encode(\'utf8\'))

while True:
    sock,addr = server.accept()
    current_thread = threading.Thread(target=handle_sock, args=(sock,addr))
    current_thread.start()

以上是关于python之socket编程的主要内容,如果未能解决你的问题,请参考以下文章

Python—网络编程之tcp编程

python之网络编程

python之socket编程

Python 基础之socket编程

python之socket编程

python之socket编程