C和python代码之间的套接字通信

时间:2016-06-27 15:32:02

标签: python c string sockets

我有一个python套接字服务器,它将字符串发送到打印字符串的C程序(客户端),然后将其发送回打印它的python程序。通信工作,但如果它发送一个长字符串,然后是一个短字符串,当前和以前的数据类型合并。这是一个例子:

输出:

5.0standing0.0                //That is how it should look like
5.0walk0ing0.055111512313e-17 //After the long string

python代码(只是在循环中调用):

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port
server_address = ('localhost', 8888)
print >>sys.stderr, '\nstarting up on %s port %s\n' % server_address
sock.bind(server_address)

# Listen for incoming connection
sock.listen(1)

def send_control(state,xdiff,xactual):
  connection, client_address = sock.accept()
  connection.sendall(str(xactual)+str(state)+str(xdiff))
  data = connection.recv(2000)
  print data
  data = '\0'

C代码(也在循环中调用):

void comm_func() 
{
  int sock;
  int i=0;
  struct sockaddr_in server;
  char message[1024] , server_reply[2000];

  //Create socket
  sock = socket(AF_INET , SOCK_STREAM , 0);
  if (sock == -1)
  {
      printf("Could not create socket");
  }
  // puts("Socket created");

  server.sin_addr.s_addr = inet_addr("127.0.0.1");
  server.sin_family = AF_INET;
  server.sin_port = htons( 8888 );

  //Connect to remote server
  if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
  {
      perror("connect failed. Error");
  }

  // Receive a reply from the server
  if( recv(sock , server_reply , 2000 , 0) < 0)
  {
      puts("recv failed");
  }
  puts(server_reply);
  write(sock,server_reply,50);
  for (i=0; i< strlen(server_reply); i++)
  {
    server_reply[i] = '\0';
  }
  close(sock);
}

有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

更改

  // Receive a reply from the server
  if( recv(sock , server_reply , 2000 , 0) < 0)
  {
      puts("recv failed");
  }

分为:

  ssize_t len;
  // Receive a reply from the server
  if( (len = recv(sock , server_reply , 2000 , 0)) < 0)
  {
      puts("recv failed");
      close(sock);
      return -1;
  }
  server_reply[len] = 0;

正如@LP和@ack在评论中提到的那样,问题是短消息不是NUL终止,这对于套接字通信来说是正常的,其中0是要发送的有效字节。