2

服务器(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 客户端。抱歉,尽管它显然非常基本和简单,但我在谷歌上没有运气。谢谢。

4

2 回答 2

3

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

于 2012-04-18T00:37:09.347 回答
2

问题是您使用的是用于 Java 对象的 ObjectInputStream,而不是像 68657920 这样的原语。

于 2012-04-18T00:39:00.827 回答