我建立在Java的客戶端服務器應用程序,這裏是我的代碼的Java連接在客戶端服務器應用程序拒絕
客戶
import java.net.*;
import java.io.*;
class ClientCode{
public static void main(String args[]) throws Exception {
int character;
Socket socket = new Socket("112.134.214.53", 8765);
//i have put my public ip instead of 127.0.0.1 in order to test it is working through the internet or not
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
String string = "Hello!\n";
byte buffer[] = string.getBytes();
out.write(buffer);
while ((character = in.read()) != -1){
System.out.print((char) character);
}
socket.close();
}
}
服務器
import java.io.*;
import java.net.*;
public class ServerCode{
public static void main(String[] args){
try{
ServerSocket socket = new ServerSocket(8765);
Socket insocket = socket.accept();
BufferedReader in = new BufferedReader (new InputStreamReader(insocket.getInputStream()));
PrintWriter out = new PrintWriter(insocket.getOutputStream(), true);
String instring = in.readLine();
out.println("The server got this: " + instring);
insocket.close();
}
catch (Exception e) {}
}
}
都是使用我的家庭adsl單端口路由器連接到互聯網的同一臺計算機上運行。
服務器應用程序運行正常,但當我的客戶端通過公網IP,問題就開始連接到服務器,下面是錯誤消息
Exception in thread "main" java.net.ConnectException: Connection refused: 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 ClientCode.main(ClientCode.java:6)
我的卡巴斯基網絡監控器顯示我,我的端口8765是確定和工作
監聽服務器的IP地址? –
您是否缺少部分異常?看起來它被切斷了。 –
@Shakedown不,這是我從日食IDE得到的 – VibeeshanRC