简体   繁体   中英

Python UDP server cannot accept client connection

I want my server script to find a client which has connected to the server and then have the server send back a message to the client.

I sucessfully connected and can send bytes from client to server but I have had trouble sending from server to client. I have tried to use clientSocket, address = mySocket.accept() to find the client which has connected but then I get back the error message:

  • OSError: [WinError 10045] The attempted operation is not supported for the type of object referenced

Server

import socket

mySocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
myIP = socket.gethostname()
myPort = 1234

mySocket.bind((myIP, myPort))



while True:

    clientSocket, address = mySocket.accept()

    clientSocket.send(bytes("Connected", "utf-8"))

Client

import socket



myIP = socket.gethostname()
myPort = 1234
s1 = "string1"
s2 = "string2"
s3 = "string3"

mySocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mySocket.sendto(bytes(s1, "utf-8"), (myIP, myPort))
mySocket.sendto(bytes(s2, "utf-8"), (myIP, myPort))
mySocket.sendto(bytes(s3, "utf-8"), (myIP, myPort))


I've seen tutorials to used accept() for this purpose but it hasn't worked for me.

Using SOCK_DGRAM creates a UDP, not TCP, socket. You can't use send() on a UDP socket because they are never in a "connected" state. Which also means you can't use accept() because UDP sockets are not connection oriented. You probably want a SOCK_STREAM type socket. If you really want a UDP (datagram) socket see https://www.geeksforgeeks.org/udp-server-client-implementation-c/ for one tutorial on how they work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM