1

我正在做一个简单的 Python 套接字服务器和客户端,它们需要能够接收少量输入并且不会丢失连接。我可以输入一个命令,但在收到回复后连接丢失。我怎样才能让它活着?

客户端代码

import socket  
import sys 
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except sockets.error , msg:
    print 'Failed to create socket, Error code:' + str(msg[0]) + ' , Error message :' +     msg[1]
    sys.exit()

print 'Socket Created'

host = '127.0.0.1'
port = 8888
try:
    remote_ip = socket.gethostbyname( host )

except socket.gaierror:

    print 'Hostname could not be resolved. Exiting'
    sys.exit()

print 'Ip address of ' + host + ' is ' + remote_ip

s.connect((remote_ip , port))

print 'Socket Connected to ' + host + ' on ip ' + remote_ip

message = raw_input('Sladu inn skipun :')

try :
   s.sendall(message)
except socket.error:
   print 'Send failed'
   sys.exit()

print 'Message send successfully'

reply = s.recv(4096)

print reply

s.close()

服务器代码

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
import socket
import sys
from thread import *
import glob

HOST = ''   # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'


s.listen(10)
print 'Socket now listening'


def clientthread(conn):

    while True:
        data = conn.recv(1024)
        if data == "show dir":
            reply = glob.glob('*.*')
        else: 
           reply ="Þessi skipun hefur ekki verið forrituð"
           if not data:
              break

        conn.send(str(reply))


while 1:

    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])


    start_new_thread(clientthread ,(conn,))

s.close()
4

1 回答 1

4

您的服务器代码看起来不错。但是您的客户只发送一条消息然后退出。关闭连接。

在您的客户端代码中尝试这样的事情:

while True:
    message = raw_input('Sladu inn skipun :')
    try :
        s.sendall(message)
        print s.recv(1024)
    except socket.error:
        print 'Send failed'
        sys.exit()
于 2013-09-17T22:43:59.413 回答