# -*- coding: utf-8 -*-
from socket import *
client = socket()
ip_port = ("127.0.0.1", 9000)
client.connect(ip_port)
while 1: # 循环通讯
inp = input(">>:").strip()
if not inp:
continue
if inp.upper() == "Q":
break
client.send(inp.encode())
from_server_msg = client.recv(1024)
print("来自服务端的消息:", from_server_msg)
client.close()
客户端
服务端:
# -*- coding: utf-8 -*-
import os
from socket import *
from multiprocessing import Process
def talk(conn):
while 1: # 循环通讯
try:
from_client_msg = conn.recv(1024)
if not from_client_msg:
break
print("进程<%s>来自客户端的消息:%s" % (os.getpid(), from_client_msg))
conn.send(from_client_msg.upper())
except:
break
conn.close()
if __name__ == '__main__':
'''一个进程里开多线程实现socket通讯'''
server = socket(AF_INET, SOCK_STREAM)
ip_port = ('192.168.1.105', 9000)
server.bind(ip_port)
server.listen(5)
while 1: # 循环连接
conn, addr = server.accept()
p = Process(target=talk, args=(conn,))
p.start()
server.close()
# 进程<7412>来自客户端的消息:b'aaa'
# 进程<6972>来自客户端的消息:b'bbb'
# 进程<2132>来自客户端的消息:b'vvv'
# 进程<7492>来自客户端的消息:b'eee'
# 进程<3660>来自客户端的消息:b'xxx'
# 进程<1940>来自客户端的消息:b'zzz'