我已成功将我的Android手机作为客户端连接到覆盆子pi作为服务器。
下一步是使用字节将数据发送到raspberry pi。我是否正确地在Java中使用Android?
socket.getOutputStream().write(String.valueOf(progress).getBytes());
此后,在我的覆盆子pi方面,我将不得不接收C中的字节。我在服务器上接收数据时遇到问题。这是我的代码。
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
int main(){
int welcomeSocket,clientSocket;
char buffer[1024];
struct sockaddr_in serverAddr;
struct sockaddr_storage serverStorage;
socklen_t addr_size;
ssize_t nread;
/*---- Create the socket. The three arguments are: ----*/
/* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
welcomeSocket = socket(PF_INET, SOCK_STREAM, 0);
/*---- Configure settings of the server address struct ----*/
/* Address family = Internet */
serverAddr.sin_family = AF_INET;
/* Set port number, using htons function to use proper byte order */
serverAddr.sin_port = htons(9999);
/* Set IP address to localhost */
serverAddr.sin_addr.s_addr = INADDR_ANY;
/* Set all bits of the padding field to 0 */
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
/*---- Bind the address struct to the socket ----*/
bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
/*---- Listen on the socket, with 5 max connection requests queued ----*/
if(listen(welcomeSocket,5)==0){
printf("Listening\n");
}
else
printf("Error\n");
/*---- Accept call creates a new socket for the incoming connection ----*/
addr_size = sizeof serverStorage;
clientSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size);
printf("Successfully Connected!!!\n\r");
//Receive data from android
//recv(welcomeSocket,buffer,1024,0);
nread = recvfrom(clientSocket, buffer,1024, 0, (struct sockaddr *) &serverStorage, &addr_size);
if(nread==-1)
perror("Error!");
else
printf("Data received: %s",buffer);
return 0;
}
从Pravin的评论中,我尝试使用Recvfrom和perror,它显示错误为-1。
答案 0 :(得分:0)
好!我意识到了这个问题。我意识到我没有使用之前创建的客户端套接字。我继续使用服务器的套接字lol。起初没有注意到它。我用一个例子来看看我的服务器和示例服务器之间有什么不同,这确实有帮助!
http://www.binarytides.com/server-client-example-c-sockets-linux/