public static void main(String[] args) throws UnknownHostException {
InetAddress locAdd = InetAddress.getLocalHost();
InetAddress biaduAdd = InetAddress.getByName("www.baidu.com");
System.out.println("我的Ip地址"+locAdd.getHostAddress());
System.out.println("本地主机名"+locAdd.getHostName());
System.out.println("百度的Ip地址"+biaduAdd.getHostAddress());
try {
System.out.println("本机是否可达"+locAdd.isReachable(2000));
} catch (IOException e) {
e.printStackTrace();
}
}
String keyword = "hello 所有人"; try { String encode = URLEncoder.encode(keyword,"UTF-8"); System.out.println("after encoding====="+encode); String decode = URLDecoder.decode(encode,"UTF-8"); System.out.println("after docode====="+decode); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
运行结果:
//after encoding=====hello+%E6%89%80%E6%9C%89%E4%BA%BA
//after docode=====hello 所有人
java中使用socket(套接字)完成TCP程序的开发,使用此类可以方便的建立可靠的、持续的、双向的、点对点的通信连接。
public Socket accept() throws IOException;
在服务器端,每次运行时都要使用accept()方法等待客户端连接,此方法执行后,服务器将进入阻塞状态,直到客户端连接后程序才可以向下继续执行。返回值为客户端对象。
public class HelloServer { public static void main(String[] args) { ServerSocket server = null; Socket client = null; PrintStream out =null; try { server = new ServerSocket(8888); System.out.println("服务器运行,等待客户端连接"); client =server.accept(); String str = "hello World"; out = new PrintStream(client.getOutputStream()); out.println(str); out.close(); client.close(); server.close(); } catch (IOException e) { e.printStackTrace(); } } }
在客户端,可以通过Socket类的getInputStream()方法取服务器的输出信息,在服务端可以用getOutputStream()方法取得客户端的输出信息;
public class HelloClient { public static void main(String[] args) throws IOException { Socket client = new Socket("localhost",8888); BufferedReader buf = null; buf = new BufferedReader( new InputStreamReader( client.getInputStream())); String str = buf.readLine(); System.out.println("服务器端输出内容:"+str); client.close(); buf.close(); } }
待续。。。
原文:https://www.cnblogs.com/fengyupinglan/p/14437679.html