udp 服务端如何知道客户端socket
如题:
如果是tcp,通过accept得到一个socket,然后向客户端发信息是就用这个socket,但是udp没有accept,当我要分发消息到多个客户端时要如何做?还请各位高手赐教。
还有一个问题不太明白,udp向客户端发消息是可以用自己bind的socket的,为啥?,那如果多个客户端它会发到哪里去?
附上自己写的一些代码:
UDPserver
int main() { #ifdef WIN32 WSADATA wsaData;#endif// hostent* HostEnt; protoent* ProtoEnt;#ifdef WIN32 if(WSAStartup(MAKEWORD(2,2),&wsaData)) { printf("Init WinSock failed!\n"); return 1; }#endif SOCKET s = 0; sockaddr_in sin = {0}; sin.sin_family = AF_INET; sin.sin_port = htons(24); sin.sin_addr.S_un.S_addr = INADDR_ANY; s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (bind(s, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR) { return 0; } char buffer[1024] = "\0"; sockaddr_in addr = {0}; int nLen = 0; nLen = sizeof(sockaddr_in); while (true) { int nRecv = 0; nRecv = recvfrom(s, buffer, 1024, 0, (sockaddr*)&addr, &nLen); //printf("a"); if (nRecv > 0) { buffer[nRecv] = '\0'; printf("abc"); sendto(s, buffer, strlen(buffer), 0, (sockaddr*)&addr, sizeof(addr)); } } }
if __name__=='__main__': import socket sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.connect(('localhost',24)) import time time.sleep(2) sock.sendall('1000000') while True: str=sock.recv(1024) if str: print str break print "break" sock.close()