这是我的 C 服务器代码。我正在使用套接字连接将字符串从 java 发送到 c。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 6865
#define BUF 2048
int main(int argc, char *argv[])
{
struct sockaddr_in host, remote;
int host_fd, remote_fd;
int size = sizeof(struct sockaddr);;
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))
{
printf("bind error\n");
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");
int read = recv(remote_fd,&data,BUF, 0);
// data[read]='\0';
printf("read = %d, data = %s\n", read, data);
shutdown(remote_fd, SHUT_RDWR);
close(remote_fd);
return 0;
}
这是我向服务器发送字符串的 java 代码。
package com.java.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientFirst
{
public static void main(String[] argv)
{
DataOutputStream os = null;
try
{
Socket socket = new Socket("10.9.79.80", 6865);
os = new DataOutputStream(socket.getOutputStream());
//String ch="shanx";
os.writeUTF("harsh");
/*char ch;
in=new DataInputStream(socket.getInputStream());
System.out.println(""+in.readChar());*/
os.close();
socket.close();
} catch (UnknownHostException e) {
System.out.println("Unkonw exception " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException caught " + e.getMessage());
}
}
C 代码仅显示 2,3 个字符和一些垃圾数据,例如字符串中的未知符号。请帮我解决这个问题
最佳答案
DataOutputStream.writeUTF
不只是以 C 能够理解的方式写出字符:
- 它使用 UTF-8 的修改版本
- 将字符串的长度放在前面
您可以用 C 编写代码来处理它,但您需要非常明确地这样做。 (您可能会发现其他人已经这样做了。)
或者,您可以使用 OutputStreamWriter
并以您想要的任何正常编码写出数据,可能使用其他一些方案来指定字符串的长度。不过,您需要先确定您的要求——是否需要处理非 ASCII 文本?您要通过同一个套接字发送多个字符串吗?
另请注意,在 C 端,您应该在读取的数据后执行适当的 0 终止,以便将其作为普通“C 字符串”处理。
关于java - 在套接字编程中,我在服务器端接收字符串时出错,该字符串的代码是用 c 编写的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20631010/