Python套接字服务器/客户端编程 [英] Python socket server/client programming

查看:105
本文介绍了Python套接字服务器/客户端编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我只是进入python并尝试一些东西.首先,我要创建一个服务器,该服务器执行简单的工作,例如"GET"存储的文本,"STORE"新的文本覆盖旧的存储文本以及"TRANSLATE"的小写文本转换为大写字母.但是我有几个问题.到目前为止,这是我的代码:

So I am just getting into python and trying out some stuff. To start, I am making a server that does simple stuff like "GET"s stored text, "STORE"s new text over the old stored text, and "TRANSLATE"s lowercase text into uppercase. But I have a few questions. Here is my code so far:

import socket

HOST = ''   # Symbolic name meaning the local host
PORT = 24069    # 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]) + 'Error message: ' + msg[1]
    sys.exit()
print 'Socket bind complete'
s.listen(1)
print 'Socket now listening'
while 1:
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
    data = conn.recv(1024)
    reply = 'OK...' + data
    if not data: break
    conn.send(data)
conn.close()
s.close()

根据我的其他编程知识,要开始将客户端的文本更改为大写,我假定将客户端的文本存储在变量中,然后在其上运行一个函数以将其更改为大写. python中有这样的功能吗?有人可以给我摘录一下它的外观吗?

To start changing text from a client into uppercase, from my other programming knowledge, I assume I'd store the client's text in a variable and then run a function on it to change it to uppercase. Is there such a function in python? Could someone please give me a snippet of how this would look?

最后,我将如何在python中执行类似GET或STORE的操作?我最好的猜测是:

And lastly, how would I do something like a GET or STORE in python? My best guess would be:

data = conn.recv(1024)
if data == GET: print text
if data == STORE: text = data #Not sure how to reference the text that the client has entered

非常感谢您的帮助! :)

Thank you so much for any help! :)

自我注释:

import socket

HOST = ''   # Symbolic name meaning the local host
PORT = 24069    # 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]) + 'Error message: ' + msg[1]
    sys.exit()
print 'Socket bind complete'
s.listen(1)
print 'Socket now listening'

# Accept the connection
(conn, addr) = s.accept()
print 'Server: got connection from client ' + addr[0] + ':' + str(addr[1])
storedText = 'Hiya!'
while 1:
    data = conn.recv(1024)
    tokens = data.split(' ', 1)
    command = tokens[0]
    if command == 'GET':
        print addr[0] + ':' + str(addr[1]) + ' sends GET'
        reply = storedText
    elif command == 'STORE':
        print addr[0] + ':' + str(addr[1]) + ' sends STORE'  
        storedText = tokens[0]
        reply = '200 OK\n' + storedText
    elif command == 'TRANSLATE':
        print addr[0] + ':' + str(addr[1]) + ' sends TRANSLATE'
        storedText = storedText.upper()
        reply = storedText
    elif command == 'EXIT':
        print addr[0] + ':' + str(addr[1]) + ' sends EXIT'
        conn.send('200 OK')
        break
    else:
        reply = '400 Command not valid.'

    # Send reply
    conn.send(reply)
conn.close()
s.close()

推荐答案

我发现您是Python的新手.您可以尝试找到一些代码示例,并且应该还要学习如何解释错误消息.错误消息将为您提供应查看的行号.您应该考虑该行或上一行,因为该错误可能是由先前的错误引起的.

I see that you're quite new to Python. You can try to find some code example, and you should also learn how to interpret the error message. The error message will give you the line number where you should look at. You should consider that line or previous line, as the error may be caused by previous mistakes.

无论如何,编辑后,您仍然有缩进错误吗?

Anyway, after your edits, do you still have indentation error?

关于您的真正问题,首先是概念.

On your real question, first, the concept.

要运行客户端/服务器,您将需要两个脚本:一个作为客户端,一个作为服务器.

To run client/server, you'll need two scripts: one as the client and one as the server.

在服务器上,脚本只需要绑定到套接字并监听该连接,接收数据,处理数据,然后返回结果即可.除了您只需要在发送响应之前处理数据之外,这就是您已经正确完成的操作.

On the server, the script will just need to bind to a socket and listen to that connection, receive data, process the data and then return the result. This is what you've done correctly, except that you just need to process the data before sending response.

对于初学者,您无需在while循环中包含accept,只需接受一个连接,然后一直保持该连接,直到客户端关闭即可.

For starter, you don't need to include the accept in the while loop, just accept one connection, then stay with it until client closes.

因此,您可以在服务器中执行以下操作:

So you might do something like this in the server:

# Accept the connection once (for starter)
(conn, addr) = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
stored_data = ''
while True:
    # RECEIVE DATA
    data = conn.recv(1024)

    # PROCESS DATA
    tokens = data.split(' ',1)            # Split by space at most once
    command = tokens[0]                   # The first token is the command
    if command=='GET':                    # The client requests the data
        reply = stored_data               # Return the stored data
    elif command=='STORE':                # The client want to store data
        stored_data = tokens[1]           # Get the data as second token, save it
        reply = 'OK'                      # Acknowledge that we have stored the data
    elif command=='TRANSLATE':            # Client wants to translate
        stored_data = stored_data.upper() # Convert to upper case
        reply = stored_data               # Reply with the converted data
    elif command=='QUIT':                 # Client is done
        conn.send('Quit')                 # Acknowledge
        break                             # Quit the loop
    else:
        reply = 'Unknown command'

    # SEND REPLY
    conn.send(reply)
conn.close() # When we are out of the loop, we're done, close

并在客户端中:

import socket

HOST = ''   # Symbolic name meaning the local host
PORT = 24069    # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
while True:
    command = raw_input('Enter your command: ')
    if command.split(' ',1)[0]=='STORE':
        while True:
            additional_text = raw_input()
            command = command+'\n'+additional_text
            if additional_text=='.':
                break
    s.send(command)
    reply = s.recv(1024)
    if reply=='Quit':
        break
    print reply

在客户端控制台上运行示例(首先运行服务器,然后运行客户端):

Sample run (first run the server, then run the client) on client console:


Enter your command: STORE this is a text
OK
Enter your command: GET
this is a text
Enter your command: TRANSLATE
THIS IS A TEXT
Enter your command: GET
THIS IS A TEXT
Enter your command: QUIT

希望您可以从那里继续.

I hope you can continue from there.

另一个重要的一点是,您正在使用TCP(socket.SOCK_STREAM),因此您实际上可以在使用s.accept()接受连接后保留该连接,并且只有在完成该连接上的任务后才应关闭它(接受新连接会有其开销).您当前的代码将只能处理单个客户端.但是,我认为对于初学者来说,这已经足够了.在对此有信心之后,可以尝试使用线程化.

Another important point is that, you're using TCP (socket.SOCK_STREAM), so you can actually retain the connection after accepting it with s.accept(), and you should only close it when you have accomplished the task on that connection (accepting new connection has its overhead). Your current code will only be able to handle single client. But, I think for starter, this is good enough. After you've confident with this, you can try to handle more clients by using threading.

这篇关于Python套接字服务器/客户端编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆