当前位置: 动力学知识库 > 问答 > 编程问答 >

sockets - Python chat client behaves not at is should

问题描述:

I've been following a tutorial on http://www.binarytides.com/code-chat-application-server-client-sockets-python/ for writing a chat server and client and got the client and server running.When i connect the client to the server it shows the prompt, so i can write a message to the server. When i do that the message gets sent but the client suddenly disconnects instead of prompting again. What could be the problem here?

#!/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"))

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.settimeout(10)

#***** connect to remote host *****

try :

s.connect((HOST, PORT))

s.settimeout(None)

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()

#***** message received *****

else :

msg = sys.stdin.readline()

s.send(msg)

prompt()

分享给朋友:
您可能感兴趣的文章:
随机阅读: