gpt4 book ai didi

java - 创建一个客户端以使用 java 发送内容

转载 作者:太空宇宙 更新时间:2023-11-04 13:55:17 25 4
gpt4 key购买 nike

我正在尝试创建一个客户端来使用 java 发送名为“Post”的对象。这是我的代码

package net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import base.Post;

public class BlogClient {

public static final String IP = "127.0.0.1";
public static final int port = 3021;

public static String host = "";



public static void main(String[] args){
try{
InetAddress addr = InetAddress.getByName("127.0.0.1");
host = addr.getHostName();
}catch(UnknownHostException e){
System.out.println("Shot");
System.exit(1);
}
try(Socket socket =new Socket(host, port);//open a socket
PrintWriter out =new PrintWriter(socket.getOutputStream(),true); //send to the server
BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));//echo from the server
BufferedReader stdIn=new BufferedReader(new InputStreamReader(System.in))//client input
){
String userInput;
//while( (userInput=stdIn.readLine()) != null ){
while( (userInput=stdIn.readLine()) != null ){

Post p = new Post(userInput);
out.println(p.toString());
out.flush();//needed, since the buffered may not be full.
System.out.println("echo:"+in.readLine());
}

}catch(UnknownHostException e){
System.err.println("Don't know about host"+ IP);
System.exit(1);
}catch(IOException e){
System.err.println("Couldnt get I/O for the connection to "+IP);
System.exit(1);
}
}
}

执行时,控制台显示:无法获取与 127.0.0.1 连接的 I/O。

有人能告诉我为什么会抛出这个异常吗?

(PS:127.0.0.1是我学校的局域网ip)

最佳答案

127.0.0.1 是本地主机。可以通过修改hosts文件来改变。但对于您的情况,我们可以做一件事,我们可以检查是否存在代码问题或网络问题。

通过使用 Windows cmd 提示符

    telnet 127.0.0.1 3021 // 3021 is the port no.

如果出现黑屏,则表示网络连接已建立,如果出现异常,则表示存在网络问题。可能是防火墙阻止了请求。

关于java - 创建一个客户端以使用 java 发送内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29890136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com