gpt4 book ai didi

Python。一次输入后套接字关闭

转载 作者:太空宇宙 更新时间:2023-11-04 10:43:49 25 4
gpt4 key购买 nike

我正在做一个简单的 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()

最佳答案

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

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

while True:
message = raw_input('Sladu inn skipun :')
try :
s.sendall(message)
print s.recv(1024)
except socket.error:
print 'Send failed'
sys.exit()

关于Python。一次输入后套接字关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18860867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com