i want to communication between two system using python socket, in which one machine is local system(client) and another is public system(server),
the code i write is :
client.py
import socket
import commands
import sys
import time
s = socket.socket()
state = sys.argv[1]
pname = sys.argv[2]
user = commands.getoutput("whoami")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('132.65.45.156', 5001))
info = commands.getoutput("echo '%s','%s','%s','%s'"%(state,ip,user,pname))
while True:
data2 = info
s.sendall(data2)
break
server.py
import socket
import time
import string
import sys
import base64
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 5001))
sock.listen(5)
while True:
newSocket, address = sock.accept()
print "Connected from ", address
filename = newSocket.recv(5001)
while True:
data = newSocket.recv(5001)
if not data: break
print filename, "Received\n"
sock.close()
After getting response from client to server, what to do if server want to send response to client ?
Related
I am new to Python. I am writing a Server program and a Client program. In here, Server plays the role of distributing the data to the multiple clients. It works great. My task is to distribute the data from the server by using server.py file. Whenever any clients wants it, he just execute clients.py in his laptop and get the results. But in here, the Server starts distributing the data. The ip, the server using was 127.0.1.1. It is not taking the network provided ip. How to make it use the ip provided by LAN. When the clients from other computer execute clients.py file . It shows Connection refused error. Note that we are all connected in the LAN. How to solve it and make clients receive the data.
Here's the sample Client Code:
import socket
import os
from threading import Thread
import socket
import time
s = socket.socket()
host = '127.0.1.1'
port = 10016
print(host)
s.connect((host, port))
while True:
print(s.recv(1024))
s.close()
Sample Server Code:
import socket
import os
from threading import Thread
import thread
import threading
import time
import datetime
def listener(client, address):
print ("Accepted connection from: ", address)
with clients_lock:
clients.add(client)
try:
while True:
client.send(a)
time.sleep(2)
finally:
with clients_lock:
clients.remove(client)
client.close()
clients = set()
clients_lock = threading.Lock()
host = socket.gethostname()
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
client, address = s.accept()
timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
a = "Hi Steven!!!" + timestamp
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
configure the ip provided by LAN to client.py (ip in LAN like this: 192.168.122.33)
host = 'ip provided by LAN'
Finally found the answer
In the '/etc/hosts' file content, i have an IP address mapping with '127.0.1.1' to my hostname. This is causing the name resolution to get 127.0.1.1. I commented this line. Now it works. Every one in my lan can receive the data
Server Code:
import socket
import os
from threading import Thread
import threading
import time
import datetime
def listener(client, address):
print ("Accepted connection from: ", address)
with clients_lock:
clients.add(client)
try:
while True:
client.send(a)
time.sleep(2)
finally:
with clients_lock:
clients.remove(client)
client.close()
clients = set()
clients_lock = threading.Lock()
host = socket.getfqdn() # it gets ip of lan
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
client, address = s.accept()
timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
a = ("Hi Steven!!!" + timestamp).encode()
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
Client Code:
import socket
import os
import time
s = socket.socket()
host = '192.168.1.43' #my server ip
port = 10016
print(host)
print(port)
s.connect((host, port))
while True:
print((s.recv(1024)).decode())
s.close()
How can I get the connected users OS type?
because when I use os.name from the OS module it shows my servers OS type not the users
Code:
import socket
import threading
from thread import start_new_thread
connect = ""
conport = 8080
def clientThread(conn):
while True:
message = conn.recv(512)
if message.lower().startswith("quit"):
conn.close()
if not message:
break
def startClient():
host = connect
port = conport
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(1)
print("[+] Server Started")
while True:
conn, addr = sock.accept()
start_new_thread(clientThread, (conn,))
sock.close()
client = threading.Thread(target=startClient)
client.start()
I basically want to send data from one python file to the other, then have the other python file send some more data back to the first file, and then the first file send data again, and this goes on until I choose to stop sending data.
server.py:
import socket
s = socket.socket()
host = "127.0.0.1"
port = 5409
s.bind((host, port))
s.listen(1)
while True:
c, addr = s.accept()
print 'Got connection from', addr
while True:
message = raw_input(">>")
s.sendall(message)
try:
print s.recv(1024)
except:
print ""
client.py:
import socket
s = socket.socket()
host = "127.0.0.1"
port = 5409
s.connect((host, port))
while True:
print s.recv(1024)
message = raw_input(">>")
s.send(message)
I have been trying for a while and I have found nothing online other than a server and client that send data once between them and then close the connection. What can I do?
in server.py
replace s.sendall(message) and s.recv(1024) with c.sendall(message) and s.recv(1024).
I recommend you to try zmq library. Great one for this kind of stuff.
Start server, then start client server will stay open until you send trough client to close server. Hope it helps!
More about zmq you can see here
Server listener
import time
import zmq
import json
from datetime import datetime
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:50165")
import re
while True:
# Wait for next request from client
message = socket.recv()
message = str(message)
print(datetime.now(),message)
# Send reply back to client
socket.send(b"Data Recieved")
Client
import zmq
from time import sleep
context = zmq.Context()
# Socket to talk to server
print("Connecting to hello world server…")
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:50165")
sleep(2)
# Do 10 requests, waiting each time for a response
for request in range(10):
print("Sending request %s …" % request)
socket.send(b"1Hello")
sleep(0.01)
# Get the reply.
message = socket.recv()
print("Received reply %s [ %s ]" % (request, message))
I am a total beginner in Python and today I tried to create a simple chat-program. So far it doesn't work too bad, but I am unable to communicate between the server and the client. I can only send from the server to the client but not in the other direction. I tried it with multithreading and these are the results:
Server:
import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 4444
s.bind((host, port))
s.listen(3)
conn, addr = s.accept()
print("Connection from: "+str(addr[0])+":"+str(addr[1]))
def recv_data():
while True:
data = s.recv(2048).decode('utf-8')
print(data)
def send_data():
while True:
msg = input(str(socket.gethostname())+"> ")
msg = str(host + "> ").encode('utf-8') + msg.encode('utf-8')
conn.send(msg)
#t1 = threading.Thread(target=recv_data)
t2 = threading.Thread(target=send_data)
#t1.start()
t2.start()
Client:
import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 4444
s.connect((host, port))
print("Connected to: "+ host)
def recv_data():
while True:
data = s.recv(2048)
data = data.decode('utf-8')
print(data)
def send_data():
while True:
msg = input(str(host)+"> ").encode('utf-8')
s.send(msg)
t1 = threading.Thread(target=recv_data)
#t2 = threading.Thread(target=send_data)
t1.start()
#t2.start()
This code works; the server can send, the client receive, but whenever I uncomment the second thread, so that it can do both I get an error:
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
I can't seem to find a solution, so please help, what am I doing wrong? :D
conn, addr = s.accept()
def recv_data():
while True:
data = s.recv(2048).decode('utf-8')
print(data)
conn is actually the socket you want to send or recv. The error occurs because you are trying to recv from the server socket, which is illegal action. Therefore you need to change s to conn if you want to make it work.
I have created a python 3.4 file and trying to import some of the variables into another python script. Both of the scripts are in the same folder but I keep getting an error.
I can use the import and it works fine. However when I try to import variables from the script using from ServerConfiguration import port, ip I get an error saying NameError: name 'ServerConfiguration' is not defined
ServerConfiguration module:
import socket
import sys
import os
serverIP = None
def serverSocket():
PORT = 8884 # Port the server is listening on
ServerEst = input('Has a server been established')
if ServerEst == 'yes':
ServerIP = input ('Enter the servers IP address')
socks = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socks.bind((ServerIP, PORT))
print('Connection Established at ' + serverIP)
else:
CreateServer = input('Would you like to create a server')
if CreateServer == 'yes':
ServerIP = input('What is you LAN IP? Please remeber if reomte user are allowed to connect port forward port "8884" ')
socks = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socks.bind((ServerIP, PORT))
print('Connection Established to ' + ServerIP)
else:
print ('Defaulting to default')
ServerIP = 'localhost'
socks = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socks.bind((ServerIP, PORT))
print('Connection Established to ' + ServerIP)
UserModule:
from ServerConfiguration import serverSocket, serverIP
import socket
import sys
import os
def sendMessage():
sockc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
MESSAGE = input('Type the message to send ')
sockc.sendto((MESSAGE.encode, "utf-8"), (serverIP, PORT))
print(MESSAGE)
ServerConfiguration.serverSocket()
sendMessage()
If you use
from ServerConfiguration import serverSocket, serverIP
you should write just
serverSocket()
without ServerConfiguration.
Another way:
import ServerConfiguration
...
ServerConfiguration.serverSocket()