我一直在尝试将C中的接收器代码转换为python .. 我用过的python代码似乎没有收到任何东西.. 发件人的C代码使用
sendto(sid,buffer,1023,0,(struct sockaddr *)&saddr,sizeof(saddr));
将以下代码转换为python时会出现什么问题。
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<errno.h>
#include<unistd.h>
#include<stdlib.h>
int main(char *argv[])
{
socklen_t sid,clen;
char buffer[1024];
struct sockaddr_in saddr,caddr;
int n;
sid=socket(AF_INET,SOCK_DGRAM,0);
if(sid<0)
perror("socket_create");
bzero((char*)&saddr,sizeof(saddr));
saddr.sin_family=AF_INET;
saddr.sin_port=htons(12346);
saddr.sin_addr.s_addr=INADDR_ANY;
if(bind(sid,(struct sockaddr *)&saddr,sizeof(saddr))<0)
perror("socket_bind");
while(1)
{
clen=sizeof(caddr);
bzero(buffer,1024);
n=recvfrom(sid,buffer,1023,0,(struct sockaddr*)&caddr,&clen);
if(n<0)
perror("receive");
printf("Array : %s\n", buffer);
}
close(sid);
return 0;
}
我试过的Python代码是
import socket
import sys
from thread import *
HOST = "127.0.0.1" # Symbolic name meaning all available interfaces
PORT = 12346 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
答案 0 :(得分:0)
您没有将C代码转换为Python。在C中,由
创建UDP套接字 sid=socket(AF_INET,SOCK_DGRAM,0);
而在Python中你是通过
创建一个TCP套接字 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
并且正在使用listen()
和accept()
作为TCP连接 - 当发件人使用UDP时,这不起作用。
你只需要将C代码直接转换为Python,e。克。
n=recvfrom(sid,buffer,1023,0,(struct sockaddr*)&caddr,&clen);
到
buffer, caddr = s.recvfrom(1023)