将C套接字程序转换为Python
我一直在尝试把这个用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()
1 个回答
0
你没有正确地把C语言的代码转换成Python。在C语言中,是通过
sid=socket(AF_INET,SOCK_DGRAM,0);
来创建一个UDP套接字,而在Python中,你却是通过
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
来创建一个TCP套接字的。你还使用了listen()
和accept()
这两个函数,这些是用来处理TCP连接的,但如果发送方使用的是UDP,这样做是行不通的。
你只需要把C语言的代码直接转换成Python,比如说:
n=recvfrom(sid,buffer,1023,0,(struct sockaddr*)&caddr,&clen);
可以转换为
buffer, caddr = s.recvfrom(1023)