gpt4 book ai didi

java - 无法使用 Socket 连接将数据发送到 c 服务器

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:51 24 4
gpt4 key购买 nike

这是我的 C 代码。它正在接收客户端发送的数据,并向客户端发送hello。

#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();

关于java - 无法使用 Socket 连接将数据发送到 c 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20651752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com