Python, I want to make Multiple Connection Chatting Program - python

I coded chatting program with socket module.
(Python)
and I saw perfect send and get data.
But I found a problem.
This is my Server.py
import socket
import threading
HOST = '127.0.0.1'
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print(addr)
def sendmsg():
while True:
data = input()
data = data.encode("utf-8")
conn.send(data)
conn.close()
def getmsg():
while True:
data = conn.recv(1024)
if data is None:
break
else:
data = data.decode("utf-8", "ignore")
print(data)
conn.close()
threading._start_new_thread(sendmsg, ())
threading._start_new_thread(getmsg, ())
while True:
pass
Just on Client can connect with server.
I want to make multiple connection.
So I changed value of s.listen(1) to s.listen(2)
but It doesn't work.
Help me TT
This is client.py
import socket
import threading
HOST = "127.0.0.1"
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
def sendMsg():
while True:
data = input()
s.sendall(str.encode(data))
s.close()
def getMsg():
while True:
data = s.recv(1024)
data = data.decode("utf-8")
print(data)
s.close()
threading._start_new_thread(sendMsg, ())
threading._start_new_thread(getMsg, ())
while True:
pass
Thank you.

Related

Python Client / Server with Multiprocessing

I cant figure out why the client is not communicating with the Server (2 seperate jupyter notebooks with own kernel), no error messages - any suggestions?
the following code is working (without multiprocessing):
Server:
import socket
HOST = '127.0.0.1'
PORT = 50000
def start_server():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
print ('waiting for client')
conn, addr = s.accept()
print('client connected #', addr[0], 'port:', addr[1])
return conn
Server0 = start_server()
Client:
import socket
HOST = '127.0.0.1'
PORT = 50000
data = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect_ex((HOST, PORT))
while True:
byte_message = s.recv(1024)
string_message = byte_message.decode('utf8')
header, time, data = string_message.split(' ')
if header == 'close':
s.shutdown(socket.SHUT_RDWR)
s.close()
print('client connection shut down')
header = ''
elif header == '<<':
print(time,float(data))
else:
pass
As soon as I pack the client into a function and run it as a process, client and server do not connect anymore(no error is given, and the server doesent get to this line:
print('client connected #', addr[0], 'port:', addr[1])
not working client:
import socket
import multiprocessing
HOST = '127.0.0.1'
PORT = 50000
def client():
data = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect_ex((HOST, PORT))
while True:
byte_message = s.recv(1024)
string_message = byte_message.decode('utf8')
header, time, data = string_message.split(' ')
if header == 'close':
s.shutdown(socket.SHUT_RDWR)
s.close()
print('client connection shut down')
header = ''
elif header == '<<':
print(time,float(data))
else:
pass
client_process = multiprocessing.Process(target= client)
client_process.start()

Server and client don't send file, how can I make it work?

I'm trying to create a client-server file transfer using python socket but i cant make it work
For example I used this from a tutorial:
Server:
import socket, os, sys
def Main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
print(IP)
host = IP
port = 50001
s = socket.socket()
s.bind((host,port))
print("server Started")
s.listen(1)
while True:
c, addr = s.accept()
print("Connection from: " + str(addr))
filename = ''
while True:
data = c.recv(1024).decode('utf-8')
if not data:
break
filename += data
print("from connected user: " + filename)
c.close()
if __name__ == '__main__':
Main()
Client:
host = '192.168.1.90'
port = 50001
s = socket.socket()
s.connect((host, port))
Filename = 'prova3.txt'
s.send(Filename.encode('utf-8'))
s.shutdown(socket.SHUT_WR)
data = s.recv(1024).decode('utf-8')
print(data)
s.close()
host = '192.168.1.90'
port = 50001
s = socket.socket()
s.connect((host, port))
Filename = 'prova3.txt'
s.send('prova3.txt')
s.shutdown(socket.SHUT_WR)
data = s.recv(1024).decode('utf-8')
print(data)
s.close()
Now this client and server connect to each other but don't send file, what's wrong?

Python Socket Call server.py and client.py in main.py

My question is that how to call server and client sequentially in main method ?
Problem is that python debugger waiting and be suck in line that calling the server(blocking the calling client line).
I tried threading but not work . Thanks for your attention.
IMPORTANT: Below codes using Python2
Main python file:
import xClient
import xServer
import threading
tempServer=xServer
tempClient=xClient
thrMain = threading.Thread(target=tempServer.innerClient.Main())
thrMain.start()
thrMain.join()
tempClient.innerClient.Main()
xClient.py : # STANDARD Client code and works correctly
import socket
import time
class innerClient:
def Main():
time.sleep(2)
host = '127.0.0.1'
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
message = "test message"
while True:
s.send(message.encode('ascii'))
data = s.recv(1024)
print('Received from the server :', str(data.decode('ascii')))
ans = raw_input('Continue(y/n) :')
if ans == 'y':
continue
else:
break
s.close()
xServer.py : # STANDARD Server code and works correctly
import socket
import threading
class innerServer:
print_lock = threading.Lock()
# thread fuction
def threaded(c):
while True:
data = c.recv(1024)
if not data:
print('See you later')
print_lock.release()
break
data = data[::-1]
c.send(data)
c.close()
def Main():
host = ""
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("socket binded to post", port)
s.listen(5)
print("socket is listening")
while True:
c, addr = s.accept()
print_lock.acquire()
print('Connected to :', addr[0], ':', addr[1])
thr = threading.Thread(target=threaded, args=(c,))
thr.start()
thr.join()
s.close()
TCP Socket Diagram

Python - Send Integer or String to Spark-Streaming

I can send my data through CSV file. First, write my random numbers into CSV file then send it, but is it possible to send it directly?
my socket code:
import socket
host = 'localhost'
port = 8080
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
while True:
print('\nListening for a client at',host , port)
conn, addr = s.accept()
print('\nConnected by', addr)
try:
print('\nReading file...\n')
while 1:
out = "test01"
print('Sending line', line)
conn.send(out)
except socket.error:
print ('Error Occured.\n\nClient disconnected.\n')
conn.close()
spark streaming code:
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
sc = SparkContext("local[2]","deneme")
ssc = StreamingContext(sc, 10)
socket_stream = ssc.socketTextStream("localhost",8080)
random_integers = socket_stream.window( 30 )
digits = random_integers.flatMap(lambda line: line.split(" ")).map(lambda digit: (digit, 1))
digit_count = digits.reduceByKey(lambda x,y:x+y)
digit_count.pprint()
ssc.start()
This is because socket blocks sending the data and never moves on. The most basic solution is to send some amount of data and close the connection:
import socket
import time
host = 'localhost'
port = 50007
i = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
try:
while True:
conn, addr = s.accept()
try:
for j in range(10):
conn.send(bytes("{}\n".format(i), "utf-8"))
i += 1
time.sleep(1)
conn.close()
except socket.error: pass
finally:
s.close()
To get something more interesting check non-blocking mode with timeouts.

I got problems with making a Python socket server receive commands from a Python socket client

I got problems with making a Python socket server receive commands from a Python socket client. The server and client can send text to each other but I can't make text from the client trigger an event on the server. Could any one help me? I'm using Python 3.4.
server.py
import socket
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ("Connection from", addr)
while True:
databytes = conn.recv(1024)
if not databytes: break
data = databytes.decode('utf-8')
print("Recieved: "+(data))
response = input("Reply: ")
if data == "dodo":
print("hejhej")
if response == "exit":
break
conn.sendall(response.encode('utf-8'))
conn.close()
In server.py I tried to make the word "dodo" trigger print("hejhej").
client.py
import socket
host = '127.0.0.1'
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected to "+(host)+" on port "+str(port))
initialMessage = input("Send: ")
s.sendall(initialMessage.encode('utf-8'))
while True:
data = s.recv(1024)
print("Recieved: "+(data.decode('utf-8')))
response = input("Reply: ")
if response == "exit":
break
s.sendall(response.encode('utf-8'))
s.close()
Everything here works fine but, maybe not the way you want it to. If you switch the order on a couple of the lines it will display your event string before you enter your server response.
import socket
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ("Connection from", addr)
while True:
databytes = conn.recv(1024)
if not databytes: break
data = databytes.decode('utf-8')
print("Recieved: "+(data))
if data == "dodo": # moved to before the `input` call
print("hejhej")
response = input("Reply: ")
if response == "exit":
break
conn.sendall(response.encode('utf-8'))
conn.close()

Categories

Resources