socketͨÐÅС³ÌÐò
±¾Ìû×îºóÓÉ KeyError ÓÚ 2023-2-27 23:55 ±à¼·þÎñ¶Ë:
from socket import *
import time
HOST = ""# HOST ±äÁ¿Êǿհ׵ģ¬±íʾËü¿ÉÒÔʹÓÃÈκοÉÓõĵØÖ·¡£
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(family=AF_INET, type=SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)# ¿ªÊ¼TCP¼àÌý,¼àÌý5¸öÇëÇó
while True:
print("ÕýÔÚÁ¬½Ó¿Í»§¶Ë...")
tcpCliSock, addr = tcpSerSock.accept()
print(f"...Òѳɹ¦Á¬½ÓIPµØַΪ{addr}µÄµçÄÔ")
while True:
try:
data = tcpCliSock.recv(BUFSIZ)
except ConnectionResetError:
print("¿Í»§¶ËÒÑÍ˳ö")
break
if not data:
break
print("¿Í»§¶Ë·¢À´µÄÏûÏ¢ÊÇ:", data.decode('utf-8'))
tcpCliSock.close()
¿Í»§¶Ë:
from socket import *
HOST = 'localhost'
PORT = 21567 # ¶Ë¿ÚÒ»¶¨ÒªÒ»Ñù
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
print("ÒÑÁ¬½Ó·þÎñÆ÷...")
while True:
data = input('ÇëÊäÈëÒªÏò·þÎñÆ÷·¢Ë͵ÄÄÚÈÝ: ')
if not data:
break
tcpCliSock.send(bytes(data, 'utf-8'))
tcpCliSock.close()
ÔËÐÐЧ¹û:
·þÎñ¶Ë:
ÕýÔÚÁ¬½Ó¿Í»§¶Ë...
...Òѳɹ¦Á¬½ÓIPµØַΪ***.*.*.*µÄµçÄÔ
¿Í»§¶Ë·¢À´µÄÏûÏ¢ÊÇ: Hello
¿Í»§¶Ë·¢À´µÄÏûÏ¢ÊÇ: ÄãºÃ
¿Í»§¶Ë·¢À´µÄÏûÏ¢ÊÇ: ¤³¤ó¤Ë¤Á¤Ï
¿Í»§¶ËÒÑÍ˳ö...
ÕýÔÚÁ¬½Ó¿Í»§¶Ë...
¿Í»§¶Ë:
ÒÑÁ¬½Ó·þÎñÆ÷...
ÇëÊäÈëÒªÏò·þÎñÆ÷·¢Ë͵ÄÄÚÈÝ: Hello
ÇëÊäÈëÒªÏò·þÎñÆ÷·¢Ë͵ÄÄÚÈÝ: ÄãºÃ
ÇëÊäÈëÒªÏò·þÎñÆ÷·¢Ë͵ÄÄÚÈÝ: ¤³¤ó¤Ë¤Á¤Ï À÷º¦°¡
Ò³:
[1]