![](/img/trans.png)
[英]How to do Socket connection and send data to server from Android Wear
[英]Not able to send the data to the c server using Socket connection
這是我的C代碼。 它正在接收客戶端發送的數據,並向客戶端發送問候。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include<errno.h>
#include<arpa/inet.h>
#define PORT 6865
#define BUF 1024
int main(int argc, char *argv[])
{
struct sockaddr_in host, remote;
int host_fd, remote_fd;
int size = sizeof(struct sockaddr);;
int read_t;
char send_t[]="hello";
char data[BUF];
host.sin_family = AF_INET;
host.sin_addr.s_addr = htonl(INADDR_ANY);
host.sin_port = htons(PORT);
memset(&host.sin_zero, 0, sizeof(host.sin_zero));
host_fd = socket(AF_INET, SOCK_STREAM, 0);
if(host_fd == -1)
{
printf("socket error %d\n", host_fd);
return 1;
}
if(bind(host_fd, (struct sockaddr *)&host, size))
{
perror("bind error is\n");
printf("errorno is %d\n",errno);
return 1;
}
if(listen(host_fd, 5))
{
printf("listen error");
return 1;
}
printf("Server setup, waiting for connection...\n");
remote_fd = accept(host_fd, (struct sockaddr *)&remote, &size);
printf("connection made\n");
read_t = recv(remote_fd,data,sizeof(data),0);
data[read_t]='\0';
printf("read = %d, data = %s\n", read_t, data);
if(send(remote_fd,send_t,sizeof(send_t),0)==-1)
{
printf("error in sending back\n");
return 1;
}
//memset(data[BUF],0,sizeof(data));
//read_t = recv(remote_fd,data,sizeof(data),0);
//data[read_t]='\0';
//printf("read = %d, received_data = %s \n", sizeof(data), data);
shutdown(remote_fd, SHUT_RDWR);
close(remote_fd);
return 0;
}
這是客戶端Java代碼。
package pack.client;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client
{
public static void main(String[] args) throws UnknownHostException, IOException
{
char[] data = new char[10];
OutputStreamWriter outs = null;
InputStreamReader ins= null;
Socket s = new Socket("10.9.79.80", 6865);
outs = new OutputStreamWriter(s.getOutputStream());
outs.append("Socket communication");
ins= new InputStreamReader(s.getInputStream());
int da = ins.read(data, 0, 9);
System.out.print(data);
outs.close();
ins.close();
s.close();
}
}
當客戶端與服務器建立連接時,我可以在終端上看到連接建立消息,但是服務器未接收到數據。
寫入服務器后,需要刷新輸出流。
outs.append("Socket communication");
// or try this outs.write("Socket communication");
outs.flush();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.