I am trying to connect the socket via the following code
try:
# create an INET, STREAMing socket
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# now connect to the web server on port 80 - the normal http port
self.client.connect((host, port))
user = ['User.loginByToken', access_token]
self.client.sendall(user)
# self.client._locust_environment = self.environment
except Exception as e:
color_print("\n[!] Check Server Address or Port", color="red", underline=True)
it throws an error memoryview: a bytes-like object is required, not 'list'. what can I do to solve it?
You need to convert user var to bytes in order to send thru a socket:
You can try this:
import json
user = json.dumps({'User.loginByToken': access_token})
user = user.encode("utf-8")
Related
I am new to network programming in python and I am trying to create a payment gateway for a project. I have run into an error with sending and receiving data between servers.
Here is my code for both the server and the client:
Server Script:
import socket
banka_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
banka_socket.bind(("192.168.0.22", 8082))
banka_socket.listen()
print("Waiting for bank A socket...")
connection_socket, address = banka_socket.accept()
print("Bank A connected")
message = banka_socket.recv(1024).decode()
print(message)
Client Script:
import socket
gateway_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
gateway_socket.connect(("192.168.0.22", 8082))
print("Gateway connected")
client_data = "hello"
message = client_data.encode()
gateway_socket.send(message)
The data is being sent and received on the same computer. I ran the server script and then I ran the client script. That's when I received the following 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
The code with the error was:
message = banka_socket.recv(1024).decode()
Please let me know how I fix my code, I've been struggling with this for a while now.
I am new to sockets and don't really know how to receive multiple messages from the same client. I only receive the first message and not the rest.
Server code:
import socket
IP = "127.0.0.1"
PORT = 65432
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((IP, PORT))
server.listen()
while True:
communication_socket, address = server.accept()
msg = communication_socket.recv(1024).decode("utf-8")
print(msg)
Client code:
import socket
import time
HOST = "127.0.0.1"
PORT = 65432
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST, PORT))
socket.send("success".encode("utf-8"))
time.sleep(2)
socket.send("?".encode("utf-8"))
socket.close()
communication_socket, address = server.accept()
msg = communication_socket.recv(1024).decode("utf-8")
The current code accepts the new connection and then does a single recv. That's why it gets only the first data. What you need are multiple recv here after the accept.
... multiple messages from the same client
TCP has no concept of messages. It is only a byte stream. There is no guaranteed 1:1 relation between send and recv, even if it might look like this in many situations. Thus message semantics must be an explicit part of the application protocol, like delimiting messages with new lines, having only fixed size messages or similar.
I have setup a tcp socket between a client and a server, very basic. Client side:
#!/usr/bin/env python3
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = "81.88.95.250"
port = 25000
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
msg = s.recv(1024)
s.close()
print (msg.decode('ascii'))
server side:
#!/usr/bin/env python3
import socket
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 25000
# 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))
msg = 'Thank you for connecting'+ "\r\n"
clientsocket.send(msg.encode('ascii'))
clientsocket.close()
My target is to send notification from client to server, and that's easy. The difficult part is that I also need in some circumstances to start the connection from the server and to send a command to the client and this must be executed as soon as it is received, so I cannot setup a periodic "poll". But I'm quite confused on this part, because the client is behind a NAT, not exposed with a public IP.
The udp server and client on my local pc.
cat server.py
import socket
MAX_BYTES =65535
def server():
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('127.0.0.1',10000))
print('Listening at {}'.format(sock.getsockname()))
while True:
data,address = sock.recvfrom(MAX_BYTES)
text = data.decode('ascii')
print('The client at {} says {!r} '.format(address,text))
if __name__ == "__main__":
server()
Bind port 10000 with localhost-127.0.0.1,and listening to the message send from client.
cat client.py
import socket
import time
from datetime import datetime
MAX_BYTES =65535
def client():
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('127.0.0.1',10001))
text = 'The time is {}'.format(datetime.now())
data = text.encode('ascii')
while True:
time.sleep(10)
sock.sendto(data,('127.0.0.1',10000))
print('The OS assinged me the address {}'.format(sock.getsockname()))
if __name__ == "__main__":
client()
Run the server.py and client.py on my local pc,server can receive message send from client.
Now i change 127.0.0.1 in the line in client.py with my remote vps_ip.
sock.sendto(data,('127.0.0.1',10000))
into
sock.sendto(data,('remote_ip',10000))
Push server.py into my vps.Start client.py on my local pc,server.py on remote vps,start them all.
In my client,an error info occurs:
File "client.py", line 13, in client
sock.sendto(data,('remote_ip',10000))
OSError: [Errno 22] Invalid argument
How to make remote ip receive message send from my local client pc?
Two things that could be happening:
You're not passing the remote IP correctly. Make sure that your not passing literally 'remote_ip' and replace it with a valid IPv4 IP address string (IE: '192.168.0.100') for the server. (FYI technically on the server you can just put '0.0.0.0' to listen on all IP addresses)
You could still be binding the client to the local address to (127.0.0.1), but setting the destination to a valid external address (192.168.0.100). Remove the socket.bind line of code in the client to test this, you shouldn't need it.
If these both don't work, then add the results of a ping command running on the client and targeting the server.
import socket
host = 'address' # as you know this isn't letters but I just write it as address for now.
port = 50000
bufsize = 1024
server = socket.socket()
server.bind((host, port))
server.listen(5)
while 1:
print("Waiting Connection")
client, address = server.accept()
print("Connected")
welcomemsg = ("send messages")
client.send(bytes(welcomemsg, "utf-8"))
print("client info")
print(address)
msgfromclient = server.recv(bufsize).decode("utf8")
client.send(bytes(msgfromclient, "utf-8"))
import socket
bufsize = 1024
client = socket.socket()
while 1:
client.connect(('address', 50000))
welcomemsg = client.recv(bufsize).decode("utf8")
print(welcomemsg)
msgtoserver = input()
server.send(bytes(msgtoserver, "utf-8"))
msgfromserver = client.recv(bufsize).decode("utf8")
print(msgfromserver)
I think I can connect server and client and then I can make server send a welcome message to client and client can receive that message.
But after that I think I can't retain connection between server and client any longer.
I want to make server and client retain connection after server send a welcome message to client and client send a message to server and then server send it again to all the clients (yes I am trying to make chat program.)
I am using Windows.