Server (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());
// ...
client (C) - this is exactly the sample code from 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 is not happy:
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)
line 243 is:
ObjectInputStream in = new ObjectInputStream(connection.getInputStream());
The C client works with the C server, and the C server works with my Python client. Similar Java servers I've written have worked with Java clients. So as far as I can tell there's some magic words to get Java server -> non-Java client. Sorry, I've had no luck on the Google with this, despite it being obviously very basic and simple. Thanks.
You're using an ObjectInputStream
on the Java side, which expects a very specific protocol of serialized Java objects. Unless you write the correct format to the socket from the C client, this is exactly the error you will get. You haven't shown how you try to read from the stream, but I suspect you just want a BufferedInputStream
instead.