p2p py

Solutions on MaxInterview for p2p py by the best coders in the world

showing results for - "p2p py"
Alessandro
26 Sep 2016
1#Server Script
2import socket 
3import select 
4import sys 
5from thread import *
6
7"""The first argument AF_INET is the address domain of the 
8socket. This is used when we have an Internet Domain with 
9any two hosts The second argument is the type of socket. 
10SOCK_STREAM means that data or characters are read in 
11a continuous flow."""
12server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
13server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
14
15# checks whether sufficient arguments have been provided 
16if len(sys.argv) != 3: 
17	print("Correct usage: script, IP address, port number")
18	exit() 
19
20# takes the first argument from command prompt as IP address 
21IP_address = str(sys.argv[1]) 
22
23# takes second argument from command prompt as port number 
24Port = int(sys.argv[2]) 
25
26""" 
27binds the server to an entered IP address and at the 
28specified port number. 
29The client must be aware of these parameters 
30"""
31server.bind((IP_address, Port)) 
32
33""" 
34listens for 100 active connections. This number can be 
35increased as per convenience. 
36"""
37server.listen(100) 
38
39list_of_clients = [] 
40
41def clientthread(conn, addr): 
42
43	# sends a message to the client whose user object is conn 
44	conn.send("Welcome to this chatroom!") 
45
46	while True: 
47			try: 
48				message = conn.recv(2048) 
49				if message: 
50
51					"""prints the message and address of the 
52					user who just sent the message on the server 
53					terminal"""
54					print("<" + addr[0] + "> " + message )
55
56					# Calls broadcast function to send message to all 
57					message_to_send = "<" + addr[0] + "> " + message 
58					broadcast(message_to_send, conn) 
59
60				else: 
61					"""message may have no content if the connection 
62					is broken, in this case we remove the connection"""
63					remove(conn) 
64
65			except: 
66				continue
67
68"""Using the below function, we broadcast the message to all 
69clients who's object is not the same as the one sending 
70the message """
71def broadcast(message, connection): 
72	for clients in list_of_clients: 
73		if clients!=connection: 
74			try: 
75				clients.send(message) 
76			except: 
77				clients.close() 
78
79				# if the link is broken, we remove the client 
80				remove(clients) 
81
82"""The following function simply removes the object 
83from the list that was created at the beginning of 
84the program"""
85def remove(connection): 
86	if connection in list_of_clients: 
87		list_of_clients.remove(connection) 
88
89while True: 
90
91	"""Accepts a connection request and stores two parameters, 
92	conn which is a socket object for that user, and addr 
93	which contains the IP address of the client that just 
94	connected"""
95	conn, addr = server.accept() 
96
97	"""Maintains a list of clients for ease of broadcasting 
98	a message to all available people in the chatroom"""
99	list_of_clients.append(conn) 
100
101	# prints the address of the user that just connected 
102	print(addr[0] + " connected")
103
104	# creates and individual thread for every user 
105	# that connects 
106	start_new_thread(clientthread,(conn,addr))	 
107
108conn.close() 
109server.close()
110
111#Client Script
112# Python program to implement client side of chat room. 
113import socket 
114import select 
115import sys 
116
117server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
118if len(sys.argv) != 3: 
119	print("Correct usage: script, IP address, port number")
120	exit() 
121IP_address = str(sys.argv[1]) 
122Port = int(sys.argv[2]) 
123server.connect((IP_address, Port)) 
124
125while True: 
126
127	# maintains a list of possible input streams 
128	sockets_list = [sys.stdin, server] 
129
130	""" There are two possible input situations. Either the 
131	user wants to give manual input to send to other people, 
132	or the server is sending a message to be printed on the 
133	screen. Select returns from sockets_list, the stream that 
134	is reader for input. So for example, if the server wants 
135	to send a message, then the if condition will hold true 
136	below.If the user wants to send a message, the else 
137	condition will evaluate as true"""
138	read_sockets,write_socket, error_socket = select.select(sockets_list,[],[]) 
139
140	for socks in read_sockets: 
141		if socks == server: 
142			message = socks.recv(2048) 
143			print(message)
144		else: 
145			message = sys.stdin.readline() 
146			server.send(message) 
147			sys.stdout.write("<You>") 
148			sys.stdout.write(message) 
149			sys.stdout.flush() 
150server.close() 
151
152
153# Server (host) should have the top server script and the clients should have the client script. Both are labelled with a comment
Mika
17 Apr 2019
1from p2p_python.utils import setup_p2p_params, setup_logger
2from p2p_python.server import Peer2Peer, Peer2PeerCmd
3import logging
4import asyncio
5import aiomonitor
6import time
7 
8loop = asyncio.get_event_loop()
9log = logging.getLogger(__name__)
10 
11setup_logger(logging.INFO)
12 
13# setup Peer2Peer
14setup_p2p_params(
15    network_ver=11111,  # (int) identify other network
16    p2p_port=2000, # (int) P2P listen port
17    p2p_accept=True, # (bool) switch on TCP server
18    p2p_udp_accept=True, # (bool) switch on UDP server
19)
20p2p = Peer2Peer(listen=100)  # allow 100 connection
21p2p.setup()
22 
23# close method example
24def close():
25    p2p.close()
26    loop.call_later(1.0, loop.stop)
27 
28# You can setup DirectDmd method
29class DirectCmd(object):
30 
31    @staticmethod
32    async def what_is_your_name(user, data):
33        print("what_is_your_name", user, data)
34        return {"you return": time.time()}
35 
36    @staticmethod
37    async def get_time_now(user, data):
38        print("get_time_now", user, data)
39        return {"get time now": time.time()}
40 
41# register methods for DirectCmd
42p2p.event.setup_events_from_class(DirectCmd)
43# throw cmd by `await p2p.send_direct_cmd(DirectCmd.what_is_your_name, 'kelly')`
44# or `await p2p.send_direct_cmd('what_is_your_name', 'kelly')`
45 
46# You can setup broadcast policy (default disabled)
47# WARNING: You must set strict policy or will be broken by users
48async def broadcast_check_normal(user, data):
49    return True
50 
51# overwrite method
52p2p.broadcast_check = broadcast_check_normal
53 
54# setup netcat monitor
55local = locals().copy()
56local.update({k: v for k, v in globals().items() if not k.startswith('__')})
57log.info('local', list(local.keys()))
58aiomonitor.start_monitor(loop, port=3000, locals=local)
59log.info(f"you can connect by `nc 127.0.0.1 3000`")
60 
61# start event loop
62# close by `close()` on netcat console
63try:
64    loop.run_forever()
65except KeyboardInterrupt:
66    log.info("closing")
67loop.close()
68
queries leading to this page
how to define chat in pythonhow to make a chat system in pythoncreate a chat application in pythonhow to code a chat bot in pythonhow to make a chatbot with pythonhow to close cahtroom server pythonthe python code how to make chat application in pythonhow to create a chatbot using pythonchat app with pythonhow to make a chatting app in pythoncreate chatbot python examplesocket based chat app in pythonhow to create chat application in pythonchat server python socketchat bot in wa with pythonhow to make a chat bot using pythonmake a site embedded chatbot pythoncreate chatbot with pythonpython chatbot using annhow to create a simple chatbot in pythonsimplified chat box pythonhow to build a functional chat box in pythona chat app using pythoncreate a simple chatbot using pythoncode chatbot pythoncreating chatbot using pythonhow to make a chat app with pytthonp2p in pythhonpython chatbothow to create a chat bot in pythonpython socket chat between computers tutorialsimple python chat serverhow to make a chatbot python codechat service example pythonpublic chat app pythonchat application build using pythonchat application in pythonmaking a chat with python localhow to create chatbot using pythonhow to build a chatbot pythonhoww to make an online chat pythonchat applicatioon pythonmake a chat app pythonchat box pythonhow to develop chatbot using pythoncreating chat bot using pythoncreate chat app pythonthings needed to make a chat bot in pythonhow to make chatbot in pythonhow to create chat application using pythonchat pythonchat app in pythonchatbot code in pythonpython chatboxhow to make a chat website pythonhow to make a chat application in pythonhow to make a chat app in pythonhow to create a chat in pythonsimple chatbox python codesimple chatbot code in pythonpython chatbot documentationpython simple chat applicationcustom chatbot pythonweb chatroom python codechatbot in pythoncreate a chatbot using pythonhow to code a chat by pytornpython chat boxhow to make chat box using pythonbuild chatbot using pythonmake chatbot using pythonweb messaging system pythonmake a web chat app with pythonchat system design in pythoncreate a chatbot in pythonhow to make an im client using python tkinter and socketshow to build a chatbot with pythonhow to use python to chatpython chat application create tutorialpython chat apppython chat systemhow to make a chat bot in pythonweb chatbot in pythonhow to code a chatbot using pythonpython p2pcreate a chat box for website pythontutorial chatbot pythonmake a chat app in pythonpython import chatonline chat pythonchat box using socket in pythonchat server client pythonhow to make web chatting app using pythongroup chat project in pythonhow to chat with pythonchat room python 3how to make a chatbot pythobhow to make a simple chat program in pythonchat app using pythononline chat server project in pythohow to code a chatbot in pythonchatting app using pythonchat app pythonchatroom web python codepython online chat sourse code of chat room pythonpython simple chat programhow to make a one way chat app in pythonsimple chat application using pythonpython make real time chat appsimple chat with pythonhow to make instant messaging app pythoncreate chatbot pythonpython html interactive chatbotchatbox in pythonbasic chatbot in pythonsimple client server chat program in pythonpython 2 7 chat apphow to make chatbit with pythonmaking online chat program with pythonchat script with pythonchat app with python 5cmake chat site with pythoncreate chatbot in pythonhow to make a chatbot pythononline chatting app on pythonhow to implement chatbot in pythonmake my chat online pythonchat in socket pythonfamous chat application build using pythonpython messenger with file transfer tutorialweb based chat box using pythonpython chatbot example codehow to make messenger system using pytohnwrite a python3 program to implement chat server using socket programmingcreating chatbot using ml and pythonpython messaing applicationhow to code a chat by pythonpython messenger app sockets threadinghow to make chat application in pythonhow to make a live chat in pythonhow to make a online chat pymake chat bot in pythonchat room using pythonp2p pythonhow to create a python chatbotclient and server chat room pythonchat application with pythonpython socket chatroompyhton chat systemchat server in pythonwebsite chat room code pythonmaking a messaging app in pythonbasic chatbot python codemaking a chat server in pythonhow to code an chat programm with pythonpython chat application examplepython chat with socketspython chatbot htmlhow to make a one way chat program in pythonpython html chatbotmaking a chat app pythonwriting a chatbot in pythonuse to chat with pythonchatbot python codechat application in python like facebookmaking a chatbot using pythoncreate chatbot using python official dochow to build a chatbot using pythonhow to create a chatapp in pythonmake a simple chatbot in pythonhow to make a chatbot in python codehow to create a simple chat room in pythonmake a chat program in pythonhow to make a chat program in pythonpython socket server chat examplemake a messaging app with pythonpython3 socket chat serverlocal chat room app in pyhtonpython chat server close cleinyp2p pypython in chatbot build chatbot using python with sitehow to build a chat box using pythonpython chatbot iahow to make chat in pythonbuilding a chatbot in pythonpython chat applicationpython close chatroom serverbasic chat bot using pythonpy p2pclient and server chat roomchat app python3creating chatbot in pythonhow tto do a chatbot with pythonmake chatbot pythonpython simple chat serverhow to create chat server programm by pyton3coding a chatbot in pythonpython chatbot programchatbot in python codesocket simple chat server pythonmake a chatbot in python and htmlpython chat bot examplemake a chatbot in pythonhow to make a messenger app in pythonpython chat server close clientpython chat clienthow to make chatbot with pythonsimple chatbot using pythonhowto build chatbot pythonpython instant messenger objectivespython chatbot in websitepython advanced chat server 40 chat in pythonbuilding chat bot with pytohnsimple chatbot python codehow to make python chatbotpython chatbot tutorialpython chatsimple chatroomchat library for pythonsimple python messaging app how to build a simple chatbot in pythonhow to make a chatbot using pythonhow to make a simple chat app using pythonreal time chat app in pythoncreate chat server with pythonpython chatroom sockethow to build a chat app using pythonsimple program to chat over the nwteork pythonpython make a chat apphow to make own chatbot using pythontwo way chat application in pythonchat system in pythonpython3 chat applicationcreating a chat application in pythonhow to make chat app in pythoncreating chat app using pythonhow to write a chatbot in pythonpython chat app tutorialtcp messaging system using python socketcreate a chat box usin pythonhow to make a chat app with pythonchat application pythonhow to make a basic chat app in pythoncreate chat app with pythonhow to easily make a chat bot in pythonpython chat box example codecreate chat app using pythonpython3 chat programhow to make a chatting game in pythonpython messaging serverpython chat application createhow to make chat bot pythoncreate chatbot using pythoninteractive chatbot using pythonsocket programming chat application pythonsimple chat pyhow to create a chat bot using pythonhow to make a im client with pyhton terranovamessage app in python how to create a chat app in pythonsimple chat application pythona simple chat programs sockets pythonhow to do a chat in pythonmchatbot using pythonhow to create a chatbot pythonhiw do i make a online chat in pythonhow to make a chat to one person in pythonreal time working server and client chat room python codepython chatbot codehow to make a chat app pythononline chat python 3make chat with pythonchat with server free pythonchatbox using pythoncan we make a chatbot using python 3fmulti user chat application in pythonmaking a chat room in pythonsocket messaging system pythoncode for online live chat pythonpython3 chat apphow to make a voice chat with pythonchat using pythoncreate chatbot using python with buttonspython sockets chat serveronline chat pythonhow to create chatbot in pythonchat in pythonhow to show in chat in pythonchatting app with pythonhow to create a chat system in python for appcreating a chat system with pythonpython chatting programsimple chatroom using pythonhow to make chat bot in pythonchat application using socket programming in pythonhow to make a chat in pythona chat application in pythonhow to make a simple python chatbotsimple chatbot pythonchatroom pythonhow to make a chat server in pythonmultiple client server chat program in pythonimport chatbot pythonpythno simple chat applicationchat service pythoncreate chat bot using pythonimplementing a python chatbot in htmlhtml template for chatbot pythonmaking chat app using socket connection android and pythonpython chat serverhow to build a chatbot in pythonsimple chatbot in pythonsockets programming in python e2 80 93building a python chat serverpython chat programpython chatbot examplesimple chat bot using pythonhow to do a chat in pythonmake chatbot using python machine learningpython messaging appmulti chat room python programmhow to make a simple chatroom in pythonhow to develop a chatbot in pythoninstant messager in python 3python chatting appinstant messenger app in pythonsimple chat application in pythonchat box with pythonmake a local chat python with socketbuilding chatbot python how to make a chatbot in pythonpython network programming chathow to make a chat bot with pythonhow to create a chatbot in pythonsimple chat bot pythonhow to make a messaging app in pythonhow to make a chat with pythonchat application using pythonsimple chat in pythonpython code to a chat programcreate simple server for chating with python3making a two way chat with python using socketshow to build chatbot using pythonhow to build a chatbott with pythonhow to create a chat app using pythonhow to create a end to end chat app with pythonchat with pythonhow to create a chatbot application in pythonpython chat codesimple chat app in pythonhow to make a chat app using pythonwrite a python program to implement chat server using socket programmingmake my chat public pythonhow to code a chattbot in pythoncan you make a chatbot with pythontext based chatbot in pythoncreate chat using pythonchat program socket pythonmessaging app in pythonchat server pypython how to make a chat how to use whating in pythonmessage app pythonbuild a live chat using pythonhow to make chatbot pythonhow to make chatbot using pythonpersonal chat box in pythonpython chat roomhow to code a chat program with pythonpython make chat boxpython live chatmake a chatbot pythontype in a chatbox on pythonpyhton chatmaking chat program pythonp2p py