码迷,mamicode.com
首页 > 编程语言 > 详细

python的socket编程

时间:2019-05-08 10:52:59      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:png   for   port   span   客户   消息   tar   end   python   

 

 

技术图片

socket主要用于长连接 

简单DEMO:

Server端:

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((0.0.0.0, 8000))
server.listen()
sock, addr = server.accept()

# 获取从客户端发送的数据
data = sock.recv(1024)
print(data.decode("utf8"))

sock.send("Hi,{}".format(data.decode("utf8")).encode("utf8"))

server.close()
sock.close()

client端:

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((127.0.0.1, 8000))
client.send("feng".encode("utf8"))
data = client.recv(1024)
print(data.decode("utf8"))
client.close()

结果:

server:  feng

client:  Hi,feng

 

 

简易聊天室:

Server端:

 

import socket
import 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"))  #


# 获取从客户端发送的数据
# 一次获取1k数据
while True:
    sock, addr = server.accept()

    # 用线程去处理新接收的连接(用户)
    client_thread = threading.Thread(target=handle_sock, args=(sock, addr))
    client_thread.start()

client端:

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"))

结果:

多个client可以给server发消息

 

python的socket编程

标签:png   for   port   span   客户   消息   tar   end   python   

原文地址:https://www.cnblogs.com/lisen10/p/10829889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!