import socket
import sys
host = ''
port = 10001
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((host, port))
server_socket.listen(5)
print("服务器端就绪中----------------------------")
client_sock, client_address = server_socket.accept()
print("已和客户端建立连接中----------------------")
while True:
try:
info = client_sock.recv(1024)
if len(info):
print("客户端:" + info.decode())
send_mes = input("服务端:")
client_sock.send(send_mes.encode())
except:
print("客户端中断连接")
client_sock.close()
sys.exit(0)
import socket
import sys
host = 'localhost'
port = 10001
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("客户端就绪中------------------------------")
try:
client_socket.connect((host, port))
print("已和服务器建立连接中----------------------")
except:
sys.exit(1) # exit(1):有错误退出
while True:
try:
send_mes = input("客户端:")
client_socket.send(send_mes.encode())
info = client_socket.recv(1024)
if len(info):
print("服务端:" + info.decode())
except:
print("服务器中断连接")
client_socket.close()
sys.exit(0) # exit(0):无错误退出