Java网络通信非常简单,服务器端通过ServerSocket建立监听,客户端通过Socket连接到指定服务器后,通信双方就可以通过IO流进行通信。
IP地址用于唯一地标识网络中的一个通信实体。端口用于表示数据交给哪个通信程序处理。
公认端口从0到1023,紧密绑定一些特定的服务。注册端口从1024到49151,应用程序通常应该使用这个范围的端口。动态端口从49152到65535,是应用程序使用的动态端口,应用程序一般不会主动使用这些端口。
package com.ivy.net; import java.net.InetAddress; public class InetAddressDemo { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub InetAddress ip = InetAddress.getByName("www.google.com"); System.out.println("crazyit isReachable : " + ip.isReachable(2000)); System.out.println(ip.getHostAddress()); InetAddress local = InetAddress.getByAddress(new byte[]{127,0,0,1}); System.out.println("local isReachable : " + local.isReachable(2000)); System.out.println(local.getHostAddress()); } }
当URL地址里包含非西欧字符的字符串时,系统会将这些非西欧字符串转换成application/x-www-form-urlencoded MIME字符串。这就需要URLDecoder和URLEncoder类。只包含西欧字符的普通字符串无须转换。
package com.ivy.net; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; public class URLDecoderDemo { public static void main(String[] args) throws UnsupportedEncodingException { // TODO Auto-generated method stub String keyWord = URLDecoder.decode("%B7%E8%BF%F1Java", "GBK"); System.out.println(keyWord); String urlString = URLEncoder.encode("疯狂Java讲义", "GBK"); System.out.println(urlString); } }
通常情况下,URL可以由协议名/主机/端口和资源组成,即如下格式
protocol://host:port/resourceName
eg. http://www.crazyit.org/index.php
使用Socket通信
package com.ivy.net; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub ServerSocket ss = new ServerSocket(30000); while(true) { Socket s = ss.accept(); PrintStream ps = new PrintStream(s.getOutputStream()); ps.println("Hello"); ps.close(); s.close(); } } }
package com.ivy.net; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Socket; public class Client { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub Socket socket = new Socket("127.0.0.1", 30000); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line = br.readLine(); System.out.println("data from server : " + line); br.close(); socket.close(); } }