Reputation: 91
Initially I would like to thank you for your time...
I created a server socket in c++ in my macbook and a client/socket using Java in a diffrent machine which runs windows xp. I have specified the port to 5000 but I cant specify the correct Host and thus I can not make the connection. When I created a c++ server/socket in windows xp using WinSock2 the connection was made perfectly as I used the localhost...any ideas???
Thnx in advance
C++ code
int main( int argc, const char** argv ) {
/* SOCKET VARIABLES */
int sock;
struct sockaddr_in server;
int mysock;
char buff[1024];
int rval;
/*CREATE SOCKET*/
sock =socket(AF_INET, SOCK_STREAM, 0);
if (sock<0)
{
perror("*FAILED TO CREATE SOCKET*");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=5000;
/*CALL BIND*/
if (bind(sock, (struct sockaddr *)&server, sizeof(server)))
{
perror("BIND FAILED");
exit(1);
}
/*LISTEN*/
listen(sock, 5);
/*ACCEPT*/
do{
mysock= accept(sock, (struct sockaddr *) 0, 0);
if (mysock==-1)
{
perror ("ACCEPT FAILED");
}
else
{
memset(buff, 0, sizeof(buff));
if ((rval=recv(mysock, buff, sizeof(buff), 0)) <0) {
perror("READING STREAM MESSAGE ERROR");
}
else if(rval==0)
printf("Ending connection");
else
printf("MSG: %s\n", buff);
printf("GOT THE MESSAGE (rval = %d)\n", rval);
}
return 0;
}while (1) ;
Java code
import java.io.; import java.net.;
public class SOK_1_CLIENT {
public void run() throws Exception
{
Socket SOCK =new Socket ("localhost",5000);
PrintStream PS =new PrintStream(SOCK.getOutputStream());
PS.println("HELLO TO SERVER FROM CLIENT");
InputStreamReader IR =new InputStreamReader(SOCK.getInputStream());
BufferedReader BR = new BufferedReader(IR);
String MESSAGE =BR.readLine();
System.out.println(MESSAGE + "java");
}
}
Upvotes: 4
Views: 1586
Reputation: 448
In java client, use the IP address of the system which is running server not "localhost". Localhost will refer to the local loopback address of the machine running the client code which is 127.0.0.1, but you have your server running on different machine, hence connection is not possible:
public void run() throws Exception
{
String address = "address_of_machine_running_server";
Socket SOCK =new Socket (address,5000);
PrintStream PS =new PrintStream(SOCK.getOutputStream());
PS.println("HELLO TO SERVER FROM CLIENT");
InputStreamReader IR =new InputStreamReader(SOCK.getInputStream());
BufferedReader BR = new BufferedReader(IR);
String MESSAGE =BR.readLine();
System.out.println(MESSAGE + "java");
}
Also note that you need to set the firewall accordingly to allow the connections.
Upvotes: 1