First, I would like to thank you for your time ...
I created a server socket in C ++ on my macbook and client / socket using Java on another machine that runs Windows XP. I pointed the port to 5000, but I cannot specify the correct host, and therefore I cannot establish a connection. When I created C ++ server / socket in windows xp using WinSock2, the connection was fine, since I used localhost ... any ideas ???
Thnx in advance
C ++ code
int main (int argc, const char ** argv) {
int sock;
struct sockaddr_in server;
int mysock;
char buff[1024];
int rval;
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;
if (bind(sock, (struct sockaddr *)&server, sizeof(server)))
{
perror("BIND FAILED");
exit(1);
}
listen(sock, 5);
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");
}
}
source
share