我正在尝试通过端口和主机名连接服务器。
我找到了一个程序,但是当我尝试运行时,它会显示以下异常
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at sample.Echoclient2.main(Echoclient2.java:31)
Couldn't get I/O for the connection to: 127.0.0.1
Java Result: 1
这是我使用的代码。
public class Echoclient2 {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10008.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 10008);
System.out.println("server name"+Inet4Address.getByName(serverHostname));
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
System.out.println("Connection accepted " +
echoSocket.getInetAddress() + ":" +
echoSocket.getPort());
} catch (UnknownHostException e) {
e.printStackTrace();
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"Bye.\" to quit)");
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
// end loop
if (userInput.equals("Bye."))
break;
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
我需要什么:
1. 我需要向服务器发送一些消息并希望得到服务器的响应。假设我发送“我是 stackoverflow 的用户”,那么服务器应该给出任何响应,如返回相同的字符串或转换为大写或其他内容。
一些问题:
1.我写客户端Java文件,但我是否需要写服务器Java文件。
2.我们可以使用ip和port发送请求吗?
3.我们可以使用主机名吗?
4. 任何回显服务器名称?我需要向该服务器发送消息想知道响应。
5. 我尝试了 server,java 和 client.java 然后我得到了结果?这个解决方案适合我吗?