最初我要感谢你的时间......
我在我的macbook中使用c ++创建了一个服务器套接字,并在运行windows xp的不同机器中使用Java创建了一个客户端/套接字。我已将端口指定为5000但我无法指定正确的主机,因此无法建立连接。当我使用WinSock2在windows xp中创建一个c ++服务器/套接字时,连接完全正如我使用localhost ...任何想法???
Thnx提前
C ++代码
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代码
import java.io. ; import java.net。;
公共课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");
}
}
答案 0 :(得分:1)
在java客户端中,使用运行服务器而不是“localhost”的系统的IP地址。 Localhost将引用运行客户端代码127.0.0.1的计算机的本地环回地址,但是您的服务器在不同的计算机上运行,因此无法连接:
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");
}
另请注意,您需要相应地设置防火墙以允许连接。