这是我的c服务器端代码。我正在向java上的客户端发送问候
#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 256
int main(int argc, char *argv[])
{
struct sockaddr_in host, remote;
int host_fd, remote_fd;
int size = sizeof(struct sockaddr);;
int read_t,i;
char data[]="hello";
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, 10)) {
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", sizeof(data), data);
if(sendto(remote_fd,data,sizeof(data),0,NULL,1)==-1)
{
printf("error in sending back\n");
return 1;
}
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 com.java.client;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
public class ClientFirst
{
public static void main(String[] argv) throws UnknownHostException, IOException
{
char[] data = new char[10];
Socket s = new Socket("10.9.79.80", 6865);
InputStreamReader ins= new InputStreamReader(s.getInputStream());
int da= ins.read(data, 0, 9);
System.out.print(Integer.toString(da));
}
}
当我试图从c服务器接收数据时,我没有得到它。 而不是打招呼,我得到5。
答案 0 :(得分:1)
尝试打印data
变量,而不是变量InputStreamReader.read
中da
的返回值,如下所示:
System.out.print(data);
InputStreamReader.read
代替返回读取的字符数。
答案 1 :(得分:1)
您正在打印从流中读取的字符数,而不是实际读取的数据。试试这个:
int da = ins.read(data, 0, 9);
System.out.print( data );
干杯,
答案 2 :(得分:0)
da
为5,因为您从套接字读取了五个字节。 hello
由5个字节组成,因此一切正常。您收到的信件已存储在变量data
。