gpt4 book ai didi

java - Socket编程-Java服务器,C(或其他)客户端-服务器给 "invalid stream header"

转载 作者:行者123 更新时间:2023-11-30 06:30:46 25 4
gpt4 key购买 nike

服务器(java):

public static void main(String[] args) {


//single threaded for now

try {

//very magic #
ServerSocket service = new ServerSocket(33000);

while(true) {

debug("Begin waiting for connection");

//this spins
Socket connection = service.accept();

debug("Connection received from " + connection.getInetAddress().getHostName());

ObjectOutputStream out = new ObjectOutputStream(connection.getOutputStream());
ObjectInputStream in = new ObjectInputStream(connection.getInputStream());

// ...

客户端 (C) - 这正是来自 http://www.linuxhowtos.org/data/6/client.c 的示例代码

int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;

char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
close(sockfd);
return 0;
}

Java 不开心:

Begin waiting for connection
Connection received from localhost
Fatal Exception: invalid stream header: 68657920
java.io.StreamCorruptedException: invalid stream header: 68657920
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:801)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
at Scanner.main(Scanner.java:243)

第 243 行是:

ObjectInputStream in = new ObjectInputStream(connection.getInputStream());

C 客户端与 C 服务器一起工作,C 服务器与我的 Python 客户端一起工作。我编写的类似 Java 服务器也适用于 Java 客户端。据我所知,有一些神奇的词可以获取 Java 服务器 -> 非 Java 客户端。抱歉,尽管它显然非常基础和简单,但我在谷歌上没有运气。谢谢。

最佳答案

您正在 Java 端使用 ObjectInputStream,它需要一个非常特定的序列化 Java 对象协议(protocol)。除非您从 C 客户端向套接字写入正确的格式,否则这正是您将得到的错误。你还没有展示你是如何尝试从流中读取的,但我怀疑你只是想要一个 BufferedInputStream

关于java - Socket编程-Java服务器,C(或其他)客户端-服务器给 "invalid stream header",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10201043/

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