I want to know the Exception name that happen when a server have connection with a client in specific port, and another client wanna make a connection to server from that port ...
So i make server, client1 and client2 but when server and client1 are connected together and i run client3 amazingly without any error they all continue running.
I wanto to know why i didn`t get any error?
what's exactly the role of '1' in this line: serverSocket.listen(1)
This is server code:
import socket
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind(('', 80))
print("Host=%s" %str(serverSocket.getsockname()))
serverSocket.listen(1)
clientSocket, addr = serverSocket.accept()
print("Got a connection from %s" % str(addr))
data = clientSocket.recv(1024)
print("from Client:%s "%str(addr))
print("\n data:%s "%str(data.decode("utf-8")))
#consciously i didn't close the the sockets
client1:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 80
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(bytes("test code", 'utf-8'))
data = s.recv(BUFFER_SIZE)
print(type(data))
s.close()
client2
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 80
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(bytes("test3", 'utf-8'))
data = s.recv(BUFFER_SIZE)
print(type(data))
s.close()
sth else,why when i run client2, the server didn`t show any message that got connection from it, like:
Got a connection from ('127.0.0.1', 64358)
The code of client1 fails with error:
TypeError: str() takes at most 1 argument (2 given)
It's because that bytes in python 2 is the same as str and it accepts only one string argument, credit goes to alecxe.
Related
From client I am trying to send a txt file to server.
client.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 8340
BUFFER_SIZE = 1024
server_addr = (TCP_IP, TCP_PORT)
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect(server_addr)
file = open(r"C:\Users\sakthi\Desktop\Hi.txt",'r')
transfer = file.read(BUFFER_SIZE)
while transfer:
c.send(transfer.encode())
transfer = file.read(1024)
print (s.recv(BUFFER_SIZE).decode())
c.close()
Server.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 8340
BUFFER_SIZE = 1024 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
final = open(r"C:\Users\sakthi\Desktop\final.txt", 'a+')
while 1:
print('Connection address:', addr)
r = conn.recv(BUFFER_SIZE).decode()
if not r:break
final.write(r)
print("received data:", r)
k="file received"
conn.send(k.encode())
conn.close()
Once the file is received, server will send message "file received" to client.
Client will print the message "file received" and close the connection
When I run the code, server.py is not coming out of while loop
while 1:
print('Connection address:', addr)
r = conn.recv(BUFFER_SIZE).decode()
if not r:break
final.write(r)
print("received data:", r)
r = conn.recv(BUFFER_SIZE).decode() keeps listening for new messages, but the client has transferred all messages.
size of the file is 1.14 KB.
Can anybody tell me what's wrong in my program?
I found the solution
Note our statement that recv() blocks until either there is data available to be read or the sender has closed the connection holds only if the socket is in blocking mode. That mode is the default, but we can change a socket to nonblocking mode by calling setblocking() with argument 0.
I have modified the server.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 8340
BUFFER_SIZE = 1024 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
conn.setblocking(0)
final = open(r"C:\Users\sakthi\Desktop\final.txt", 'a+')
while 1:
try:
print('Connection address:', addr)
r = conn.recv(BUFFER_SIZE).decode()
final.write(r)
print("received data:", r)
except:
break
k="file received"
conn.send(k.encode())
conn.close()
Now I am able to receive the file and send message "file received" to client and connection is closed.
non-blocking socket,error is always
http://www.mws.cz/files/PyNet.pdf
listenr code :
import socket
host = socket.gethostbyname(socket.gethostname())
port = int(raw_input("PORT > "))
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(5)
while True:
c, addr = server.accept()
buff = 2048
print addr[0]+" connected."
c.send("Connection Established")
data = c.recv(buff)
if data:
print data
client code:
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = int(raw_input("PORT > "))
server.connect((host, port))
buff = 2048
data = server.recv(buff)
if data:
print data
and is it possible to receive data from client and listen on port at the same time ? how?
After accept() use thread to send/receive data to/from client and at the same time main thread can wait for next client running accept() again. It is standard method .
#!/usr/bin/env python
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('192.168.1.123', 5162))
clientsocket.send('getval.1')
clientsocket.close
clientsocket.bind(('192.168.1.124', 5163))
clientsocket.listen(1)
while True:
connection, address=clientsocket.accept()
value=connection.recv(1024)
print value
I'm trying to get python to send a message to the server, and in return the server responds. Yet when I execute this code it gives me
Socket.error: [Errno 10022] An invalid argument was supplied
It seems you wrote a mixed code of server and client
Here a simple sample of codes for socket programming the first on server side and the second on client
Server side code:
# server.py
import socket
import time
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()
and now the client
# client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" % tm.decode('ascii'))
The server simply remained listened for any client and when it finds out a new connection it returns current datetime and closes the client connection
Im writing a simple socket program to receive some data and reverse the contents.
When I pass the reversed contents its not being sent..
Server
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print('Got connection from', addr)
print('Received message == ',c.recv(50))
s = c.recv(50)[::-1]
c.send(s)
c.close()
client
import socket
from time import sleep
s = socket.socket()
host = socket.gethostname()
port = 1234
s.connect((host, port))
print "Sending data"
s.sendall("Hello!! How are you")
print(s.recv(1024))
The problem is two lines in your server
Your server calls recv() inside a print statement. This empties the buffer. Then you call recv() again, but it is already emptied by the previous statement and so it then blocks.
You need to call recv() and store that in s. Then use s everywhere else.
Try this for your server:
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print('Got connection from', addr)
s = c.recv(50)
print('Received message == ',s)
c.send(s)
c.close()
I'm trying the following client and server chat program. Although I get an error whenever I try to run the server program, when the client program runs it stays on a blank screen not allowing me to type anything. I've tried running server first and running client first and I get the same results. I can't read the error from the server program because it flashes the error and closes the window. Here is my code:
server:
#server
import socket
import time
HOST = ''
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
client:
#client
import socket
import time
HOST = "localhost"
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((HOST,PORT))
s.sendall('Helloworld')
data = s.recv(1024)
s.close()
print 'Recieved', repr(data)
Im not an expert but I was able to make your examples work by changing the socket from datagram to stream connection, and then encoding message being sent because strings aren't supported (although this might not effect you since I think that change was made in Python 3...I'm not 100% sure).
I believe the main issue is that you're trying to listen() but SOCK_DGRAM (UDP) doesn't support listen(), you just bind and go from there, whereas SOCK_STREAM (TCP) uses connections.
If you're just trying to get the program going, use the below code, unless there is a specific reason you'd like to use SOCK_DGRAM.
The code is below:
client
#client
import socket
import time
HOST = "localhost"
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
test = 'Helloworld'
s.sendall(test.encode())
data = s.recv(1024)
s.close()
print 'Recieved', repr(data)
server
#server
import socket
import time
HOST = ''
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connected by', addr)
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()