I have a code which has 2 classes, SocketDemo and ServerSocketDemo, when the client (SocketDemo) tried to connect to the server (ServerSocketDemo), it waits for a few seconds and then throws
java.net.ConnectionException : Connection timed out
その特定の時点で、サーバーは接続が確立されていることを示しますが、クライアントは接続をリセットし、例外をスローします
最初に、ソケットを介して同じ接続で 2 つの異なるシステムを接続することは可能ですか?
このコードフラグメントを検討して助けてください!
クライアントコード
import java.net.*;
import java.io.*;
class SocketDemo
{
public static void main(String...arga) throws Exception
{
Socket s = null;
PrintWriter pw = null;
BufferedReader br = null;
System.out.println("Enter a number one digit");
int i=(System.in.read()-48); // will read only one character
System.out.println("Input number is "+i);
try
{
s = new Socket("192.168.1.5",40000);
System.out.println(s);
pw = new PrintWriter(s.getOutputStream());
System.out.println(pw);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(br);
System.out.println("Connection established, streams created");
}
catch(Exception e)
{
System.out.println("Exception in Client "+e);
}
pw.println(i);
pw.flush();
System.out.println("Data sent to server");
String str = br.readLine();
System.out.println("The square of "+i+" is "+str);
}
}
サーバーコード:
import java.io.*;
import java.net.*;
class ServerSocketDemo
{
public static void main(String...args)
{
ServerSocket ss=null;
PrintWriter pw = null;
BufferedReader br = null;
int i=0;
try
{
ss = new ServerSocket(40000);
}
catch(Exception e)
{
System.out.println("Exception in Server while creating connection"+e);
e.printStackTrace();
}
System.out.print("Server is ready");
while (true)
{
System.out.println (" Waiting for connection....");
Socket s=null;
try
{
System.out.println("connection "+s+ "\n printwriter "+pw+"\n bufferedreader "+br);
s = ss.accept();
System.out.println("Connection established with client");
pw = new PrintWriter(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("connection "+s+ "\n printwriter "+pw+"\n bufferedreader "+br);
i = new Integer(br.readLine());
System.out.println("i is "+i);
}
catch(Exception e)
{
System.out.println("Exception in Server "+e);
e.printStackTrace();
}
System.out.println("Connection established with "+s);
i*=i;
pw.println(i);
try
{
pw.close();
br.close();
}
catch(Exception e)
{
System.out.println("Exception while closing streams");
}
}
}
}