1. 程式人生 > >tcp/socket

tcp/socket

NPU () .so cli nbsp close PE 服務 end

服務器端

import socket

server = socket.socket()
server.bind(("localhost", 6969))        #綁定要監聽的端口
server.listen(2)     #監聽多少個連接

while True:
    conn,addr=server.accept()           #等待數據
    #conn就是客戶端連過來而在服務器端圍棋生成的一個連接實例
    print(conn)
    print(addr)
    # server.accept()
    while True:
        data 
= conn.recv(1024) if data is None: print("connection lost") break print("recv", data) print(type(data)) conn.send(data.upper()) server.close()

客戶端

import socket

client = socket.socket()         #生命socket類型,生成socket連接對象
client.connect((localhost
, 6969)) while True: msg = input("type here >>").strip() if len(msg) == 0: continue client.send(msg.encode(utf-8)), # 不能send空 data = client.recv(1024) print(data.decode()) client.close()

tcp/socket