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