Python IM Program [closed]

2024/11/16 9:44:36

I want to use python sockets to create a server that multiple clients can connect to and echo text inputs. Is there a basic server I can setup with few lines of code? I already have the clients ready to connect I just need to know what a basic python socket server would look like for these client connections.

Answer

If you want more than two users I would suggest you check if it wouldn't be better to install a xmmp/jabber server instead.

Python Sockets

Pythons socket documentation also has a few simple examples which show simple chat functionality. See: http://docs.python.org/2/library/socket.html#example.

Here is a small snippet that should do the trick. It doesn't produce nice output, but it should work. It uses two threads to avoid starting up two different scripts.

# Echo server program
import socket
import threadTARGET = None
DEFAULT_PORT = 45000def 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" % datadef 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

XMLRPC

You could also look into Pythons XMLRPC capabilities if you want more than two users. For example...

Server:

This mini-server lets users send messages for users. The server then persists them into a small json file. A client can then ask for new messages for a given user.

import json
import os.pathfrom 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" % clientmessages = get()if client not in messages:messages[client] = [message]else: messages[client].append(message)save(messages)return Truedef get_messages(client):""" Get the undelivered messags for the given client. Remove them frommessages queue. """messages = get()if client in messages:user_messages = messages[client]messages[client] = []save(messages)return user_messageselse: 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()

"Client"

Example usage to send a message and get messages for a user.

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

Please Note: These are just quick examples. Both are not really secure as no sender/reciever verification is done. Also there is no trasport-security so messages can get lost.

For lots of users it would also be better to use a DBMS system instead of a simple JSON file.

As Nick ODell said, if you want a simple shell script I would also suggest you use netcat.

https://en.xdnf.cn/q/120339.html

Related Q&A

Changes in Pandas DataFrames dont preserved after end of for loop

I have a list of Pandas DataFrames and I want to perform some operations on them. To be more precise, I want to clean their names and add new column. So I have written the following code:import numpy a…

How can I prevent self from eating one of my test parameters?

I have in my test module:import pytest from src.model_code.central import AgentBasicclass AgentBasicTestee(AgentBasic):pass@pytest.fixture() def agentBasic():return AgentBasicTestee()@pytest.mark.param…

distance from a point to the nearest edge of a polygon

in the below code i want to calculate the distance from a point to the nearest edge of a polygon.as shown in the results section below, the coordinates are provided.the code posted below shows how i fi…

Is there a netcat alternative on Linux using Python? [closed]

Closed. This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meet Stack Overflow guidelines. It is not currently accepting …

keras/tensorflow model: gradient w.r.t. input return the same (wrong?) value for all input data

Given a trained keras model I am trying to compute the gradient of the output with respect to the input. This example tries to fit the function y=x^2 with a keras model composed by 4 layers of relu act…

Pandas: get json from data frame

I have data framemember_id,2015-05-01,2015-05-02,2015-05-03,2015-05-04,2015-05-05,2015-05-06,2015-05-07,2015-05-08,2015-05-09,2015-05-10,2015-05-11,2015-05-12,2015-05-13,2015-05-14,2015-05-15,2015-05-1…

Python - Statistical distribution

Im quite new to python world. Also, Im not a statistician. Im in the need to implementing mathematical models developed by mathematicians in a computer science programming language. Ive chosen python a…

How to add data in list below?

i have a list :List = [[[1,2],[2,4]],[[1,4],[4,8]],[[53,8],[8,2],[2,82]]]That i want add reverse data to listTo be:[[[1,2],[2,4],[2,1],[4,2]],[[1,4],[4,8],[4,1],[8,4]],[[53,8],[8,2],[2,82],[8,53],[2,8]…

Storing lists within lists in Python

I have a question about accessing elements in lists. This is the code: movies = ["The Holy Grail", 1975, "Terry Jones and Terry Gilliam", 91,["Graham Champman", ["Mic…

getting ZeroDivisionError: integer division or modulo by zero

I had written a simple pascal triangle code in python but I am getting a errordef factorial(n):c=1re=1for c in range(n):re = re * c;return(re)print "Enter how many rows of pascal triangle u want t…