急急急!!TCPclient和server的连接超时。。。
写一个TCP协议的套接字编程的时候,和同学的电脑一起,他的做server,我的做client,在他那运行TCPServer.java,我这运行TCPClient.java,但是会出现这个问题:
this
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at TCPClient.main(TCPClient.java:13)
//this是我在client运行的时候的输出
附代码:
TCPClient.java
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String args[]) throws Exception{
//Message from user
String message;
//Modified message from server
String modifiedMessage;
//创建客户机端的套接字对象,与服务器对应
Socket clientSocket = new Socket("61.150.43.47",5678);
//从用户键盘输入读取
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
//创建了两个连接到套接字的流对象
//outToServer为进城提供了到套接字的输出
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
//为进程提供了来自套接字的输入
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
message = inFromUser.readLine();
//将从客户机读取的message+'\n'写入到outToServer
outToServer.writeBytes(message + '\n');
//当字符到达服务器时,流过inFromServer刘,并进入modifiedMessage字符串中,遇到回车结束。
modifiedMessage = inFromServer.readLine();
System.out.println("FROM SERVER:" + modifiedMessage);
}
//关闭套接字,TCP也被关闭
// clientSocket.close();
}
TCPServer.java
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String args[]) throws Exception
{
String clientMessage;
String capitalizedMessage;
ServerSocket welcomeSocket = new ServerSocket(5678);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientMessage = inFromClient.readLine();
capitalizedMessage = clientMessage.toUpperCase() +'\n';
outToClient.writeBytes(capitalizedMessage);
System.out.println((String)clientMessage);
}
}
}
//注:我之前在自己电脑上同时运行的时候是可以的,不会出现什么问题。。。