我一直有一个程序,只要有人点击输入,而不输入任何内容,程序就会停止输入。
#Client
import socket
from time import sleep
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = 9990
s.connect((host, port))
print('connecting')
global ab
try:
ab = input('enter input')
except Exception as eb:
ab = 'hello'
s.sendall(ab.encode())
while True:
global hi
try:
hi = input('enter input')
except Exception as b:
hi = input('enter input')
try:
dataNew = s.recv(4024)
s.sendall(hi.encode())
except Exception as be:
print('try again')
if dataNew:
print(dataNew)
if not dataNew:
print('error')
break
服务器如下:
#Server
import socket
host = 'localhost'
port = 9990
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except Exception as e:
print("Error creating socket")
try:
s.bind((host, port))
print('Binding socket')
s.listen(10)
print('listening')
except Exception as e:
print('Error creating server')
def mainInput():
while True:
try:
dataNew = c.recv(4024)
c.sendall(dataNew)
if not dataNew:
print('waiting or disconnected')
break
if dataNew:
print(dataNew, a)
except Exception as b:
print('error')
def mainLoop():
while True:
global c
global a
c, a = s.accept()
print('Connected by', a)
mainInput()
mainLoop()
问题是输入空白消息会破坏程序。