python socket connection

400次阅读
没有评论
python

服务器端代码importsocket#AddressHOST=''PORT=8000reply='Yes'#Configuresockets=socket.socket(socket.AF_INET,socket.SOCK_STREAM)s.bind((HOST,PORT))#passivelywait,3:maximumnu…

服务器端代码

import socket

# Address

HOST = ''

PORT = 8000

reply = 'Yes'

# Configure socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((HOST, PORT))

# passively wait, 3: maximum number of connections in the queue

s.listen(3)

# accept and establish connection

conn, addr = s.accept()

# receive message

request = conn.recv(1024)

print ('request is: ',request)

print ('Connected by', addr)

# send message

conn.sendall(reply.encode())

# close connection

conn.close()

客户端代码

import socket

# Address

HOST = '127.0.0.1'

PORT = 8000

request = 'can you hear me?'

# configure socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((HOST, PORT))

# send message

s.sendall(request.encode())

# receive message

reply = s.recv(1024)

print ('reply is: ', reply.decode())

# close connection

s.close()

因为只有一台电脑所以连接到127.0.0.1

但提示 s.connect((HOST, PORT))

ConnectionRefusedError: [Errno 61] Connection refused

P.S. MAC系统 没有防火

展开

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python基础教程2022-11-22发表,共计1065字。
新手QQ群:570568346,欢迎进群讨论 Python51学习