1. 程式人生 > >Python socket構建簡單的伺服器客戶端互動

Python socket構建簡單的伺服器客戶端互動

client.py

#coding:utf-8
import socket
import random

print("程式開始")

#   建立套接字
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#   設定ip和埠
host = socket.gethostname()
port = 3333
#   連線到伺服器
mySocket.connect((host, port))


print("連線到伺服器")
 
while True:
    #   接收訊息
    print("----------------------讀取:\n")# 不換行輸出
    msg = mySocket.recv(1024)
    print("%s" % msg)
    print("讀取完成")
    if msg == b"EOF":
        break
    if msg == b"quit":
        mySocket.close()
        print("程式結束\n")
        exit()
 
    #   傳送訊息
    print "----------------------傳送:"
    msg = str(raw_input())
    if random.randint(1,10)>5:
        mySocket.send(msg.encode())
        print("傳送完成")
    else:
        mySocket.send("test:"+str(random.randint(1,10)))
        print("傳送完成")
    if msg == "EOF":
        break
    if msg == "quit":
        mySocket.close()
        print("程式結束\n")
        exit()
print("程式結束\n")

service.py

#coding:utf-8
import socket
print("程式開始")

#   建立套接字
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#   設定IP和埠
host = socket.gethostname()
port = 3333
#   bind繫結該埠
mySocket.bind((host, port))
#   監聽
mySocket.listen(10)
 
while True:
    #   接收客戶端連線
    print("等待連線....")
    client, address = mySocket.accept()
    print("新連線")
    print("IP is %s" % address[0])
    print("port is %d\n" % address[1])
 
    while True:
        #   傳送訊息
        print "----------------------傳送:"
        msg = str(raw_input())
        
        client.send(msg.encode())
        print("傳送完成")
        if msg == "EOF":
            break
        if msg == "quit":
            client.close()
            mySocket.close()
            print("程式結束\n")
            exit()
        #   讀取訊息
        msg = client.recv(1024)
        print("----------------------讀取:", msg)
        
        print("讀取完成")
        if msg == b"EOF":
            break
        if msg == b"quit":
            client.close()
            mySocket.close()
            print("程式結束\n")
            exit()

在這裡插入圖片描述