欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python_socket_tcp

程序员文章站 2022-07-08 07:57:35
# -*- coding:utf-8 -*- import socket HOST='127.0.0.2' #服务端的IP地址 PORT=50007 #...
# -*- coding:utf-8 -*-
import socket
HOST='127.0.0.2' #服务端的IP地址
PORT=50007  #服务端的端口号
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
    s.connect((HOST,PORT))
except Exception as e:
    print ('Server not found or not open')
    sys.exit()
while True:
    c=input('Input the content you want to send:')
    s.sendall(c.encode())    #发送数据
    data=s.recv(1024)   #接收数据
    data=data.decode()
    print ('Received:',data)
    if c.lower()=='bye':
        break
s.close()

server

# -*- coding: utf-8 -*-
# TCP protrocl

import socket
words ={'how are you?':'Fine ,thank you'}
HOST =''
PORT=50007
s =socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#绑定socket
s.bind((HOST,PORT))
#开始监听
s.listen(1)
print ('Listening at port :',PORT)
conn,addr =s.accept()
print ('Connected by',addr)
while True:
    data = conn.recv(1024)
    data=data.decode()
    if not data:
        break
    print ('Received message:',data)
    conn.sendall(words.get(data,'nothing').encode())
conn.close()
s.close()