windows --> windows 写法均在py3.6
客户端写法
import socket client = socket.socket() client.connect(('192.168.88.1', 9001)) while 1: data_recv = client.recv(1024).decode('utf-8') print(data_recv) data_sent = input('client:') client.send(data_sent.encode('utf-8')) if data_sent == 'exit': break client.close()
服务端写法
import socket server = socket.socket() server.bind(('192.168.88.1', 9001)) server.listen(5) print('等待链接中。。。。。') conn, addr = server.accept() # 监听返回 链接和 地址 print('connect succeed !') while 1: data_send = input('server:') conn.send(data_send.encode('utf-8')) data_recv = conn.recv(1024) print(data_recv.decode('utf-8')) if data_recv.decode('utf-8') == 'exit': break conn.close()
服务端Linux(py2.7) 客户端 windows(py3.6)
linux 服务端
#!usr/bin/bash pyhton #_*_ coding:utf8 _*_ # 支持中文 公网聊天 import socket import sys reload(sys) sys.setdefaultencoding('utf-8') # 为了支持中文 加入以上代码 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 参数的作用是指定协议 必须加 addr_port = ('172.17.226.72',3389) # Linux 中不准绑定公有ip 服务端必须绑定公网ip 端口必须是开放的 server.bind(addr_port) server.listen(5) conn,addr = server.accept() print('connect succeet') while 1: data_send = raw_input('server:') conn.send(data_send.encode('utf-8')) data = conn.recv(1024) print(data.decode('utf-8')) conn.close()
windows 客户端写法
import socket test = socket.socket() test.connect(('39.106.40.169', 3389)) # 链接公网ip 与对应端口 while 1: data = test.recv(1024).decode('utf-8') print(data) data_send = input('-----') test.send(data_send.encode('utf-8'))