Python IM程序

Fru*_*der -2 python sockets

我想使用python套接字来创建一个服务器,多个客户端可以连接到该服务器并回显文本输入.是否有一个基本的服务器,我可以用几行代码设置?我已经准备好连接客户了我只需要知道这些客户端连接的基本python套接字服务器是什么样的.

chk*_*orn 6

如果你想要两个以上的用户,我建议你检查一下安装xmmp/jabber服务器是否更好.

Python套接字

Pythons套接字文档还有一些简单的示例,显示简单的聊天功能.请参阅:http://docs.python.org/2/library/socket.html#example.

这是一个应该做的小片段.它不会产生很好的输出,但它应该工作.它使用两个线程来避免启动两个不同的脚本.

# Echo server program
import socket
import thread

TARGET = None
DEFAULT_PORT = 45000

def reciever():
    """ Recive messages... """

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.bind(('', DEFAULT_PORT)) # Listens on all interfaces... 
    s.listen(True) # Listen on the newly created socket... 
    conn, addr = s.accept()
    while True:
        data = conn.recv(1024)
        print "\nMessage> %s\n" % data


def sender():
    """ The 'client' which sends the messages """

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((TARGET, DEFAULT_PORT)) # Connect... 

    while True: 
        msg = raw_input("\nMe> ")
        s.sendall(msg)
    s.close()

while not TARGET:
    TARGET = raw_input("Please specify the other client to connect to: ")

thread.start_new_thread(reciever, ())
thread.start_new_thread(sender, ())

while True:
   pass
Run Code Online (Sandbox Code Playgroud)

XMLRPC

如果您需要两个以上的用户,您还可以查看Pythons XMLRPC功能.例如...

服务器:

这个迷你服务器允许用户为用户发送消息.然后服务器将它们保存到一个小的json文件中.然后,客户端可以为给定用户请求新消息.

import json
import os.path

from SimpleXMLRPCServer import SimpleXMLRPCServer

""" 
Saves messages as structure: 

{
    'client1':['message1', 'message2'], 
    'client2':['message1', 'message2']
}
"""

STORAGE_FILE = 'messages.json'

def save(messages):
    msg_file = open(STORAGE_FILE, 'w+')
    json.dump(messages, msg_file)

def get():
    if os.path.exists(STORAGE_FILE):
        msg_file = open(STORAGE_FILE, 'r')
        return json.load(msg_file)
    else: 
        return {}

def deliver(client, message):
    """ Deliver the message to the server and persist it in a JSON file..."""

    print "Delivering message to %s" % client

    messages = get()
    if client not in messages:
        messages[client] = [message]
    else: 
        messages[client].append(message)
    save(messages)

    return True

def get_messages(client):
    """ Get the undelivered messags for the given client. Remove them from
    messages queue. """
    messages = get()
    if client in messages:
        user_messages = messages[client]
        messages[client] = []
        save(messages)
        return user_messages
    else: 
        return []

server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(deliver, 'deliver')
server.register_function(get_messages, 'get_messages')
server.serve_forever()
Run Code Online (Sandbox Code Playgroud)

"客户"

用于发送消息和为用户获取消息的示例用法.

import xmlrpclib

# Connect to the 'Server'...
proxy = xmlrpclib.ServerProxy("http://localhost:8000/")

# Send a message...
proxy.deliver('username', 'The message to send')

# Recieve all messages for user..
for msg in proxy.get_messages('username'):
    print "Message> %s" % msg
Run Code Online (Sandbox Code Playgroud)

请注意:这些只是简单的例子.两者都不是很安全,因为没有发送者/接收者验证.此外,没有trasport-security,因此消息可能会丢失.

对于许多用户来说,使用DBMS系统而不是简单的JSON文件也会更好.

正如Nick ODell所说,如果你想要一个简单的shell脚本,我也建议你使用netcat.