socket_input_linux环境

#-*-coding:utf-8-*-
import socket
server=socket.socket()
server.bind((
'localhost',6969)) #绑定要监听的端口
print("正在监听端口")
server.listen(
5)              #监听 允许5个连接

print("我要开始等电话了")
while True:
    conn, addr = server.accept() 
# 等电话打进来
   
print(conn)  # conn就是客户端连过来而在服务端为其生成的一个连接实例

   
print("电话来了")
   
while True:

        data=conn.recv(
1024) #通过conn连接实例接收数据
       
print("recv:",data)
       
if not data:
           
print("client has lost...")
           
break
       
conn.send(data.upper()) #通过conn连接实例发送数据
server.close()

#-*-coding:utf-8-*-
import socket
client=socket.socket()
#默认famliy=AF_INET(ipv4)地址簇  type=SOCK_STREAM (tcp/ip) 声明socket类型,同时生成socket连接对象
client.connect(("localhost",6969))

while True:
    msg=raw_input(
"请输入:").strip()  #不能发送空数据
   
if len(msg)==0:continue    #如果msg长度为0,就继续 返回到下一次msg=raw_input("请输入:").strip()  
   
client.send(msg.encode("utf-8")) #3.x 只能发bytes类型数据,只能接收ASCII数据,汉字不行,要发汉字只能编码成utf-8格式
   
data=client.recv(1024) #1024字节数据
   
print("recv:",data.decode("utf-8")) #bytes类型打印出来要解码

client.close()


猜你喜欢

转载自blog.51cto.com/13707996/2334050
今日推荐