我一直在关注来自http://www.binarytides.com/python-socket-programming-tutorial/的python套接字教程并稍微修改了源代码,以创建客户端和服务器脚本。就我测试而言,服务器运行没有问题。但客户端给我带来了一个难以理解的无效语法错误:
文件" client.py",第17行
....试试:
..... ^
这是我的源代码:
#!/usr/bin/env python
import socket, select, string, sys
#***** prompt *****
def prompt() :
sys.stdout.write('<You> ')
sys.stdout.flush()
#***** main func *****
if __name__ == "__main__":
#if(len(sys.argv) < 3) :
# print ("Usage : python telnet.py hostname port")
# sys.exit()
HOST = raw_input("Enter host:\n")
PORT = int(raw_input("Enter port:\n")
try :
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
except socket.error, msg:
print("Failed to create socket. Error code: " + str(msg[0]) + " , Error message: " + msg[1]
#***** connect to remote host *****
try :
s.connect((HOST, PORT))
except :
print ("Unable to connect")
sys.exit()
print ("Connected to remote host. Start sending messages")
prompt()
while 1:
socket_list = [sys.stdin, s]
#***** Get the list sockets which are readable *****
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
#***** incoming message from remote server *****
if sock == s:
data = sock.recv(4096)
if not data :
print ("\nDisconnected from chat server")
sys.exit()
else :
#print data
sys.stdout.write(data)
prompt()
#***** user entered a message *****
else :
msg = sys.stdin.readline()
s.send(msg)