1. URL
类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用,例如对数据库或搜索引擎的查询。有关 URL 的类型和格式的更多信息,可从以下位置找到:
http://www.socs.uts.edu.au/MosaicDocs-old/url-primer.html
通常,URL 可分成几个部分。上面的 URL 示例指示使用的协议为 http (超文本传输协议)并且该信息驻留在一台名为 www.socs.uts.edu.au 的主机上。主机上的信息名称为 /MosaicDocs-old/url-primer.html。主机上此名称的准确含义取决于协议和主机。该信息一般存储在文件中,但可以随时生成。该 URL 的这一部分称为路径 部分。
URL 可选择指定一个“端口”,它是用于建立到远程主机 TCP 连接的端口号。如果未指定该端口号,则使用协议默认的端口。例如,http 协议的默认端口为 80。还可以指定一个备用端口,如下所示:
http://www.socs.uts.edu.au:80/MosaicDocs-old/url-primer.html
下面是一个在百度搜索Java时的一些信息反馈。
package com.java.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
/**
* 通过连接百度来读取相关内容
* @author Yuanbo Han
*
*/
public class _URL {
public static void main(String[] args) throws IOException {
String httpStr = "http://www.baidu.com/s?wd=Java";
URL url = new URL(httpStr);
System.out.println("httpStr:\t" + httpStr);
System.out.println("authority:\t" + url.getAuthority());
System.out.println("content:\t" + url.getContent());
System.out.println("port:\t\t" + url.getDefaultPort());
System.out.println("file:\t\t" + url.getFile());
System.out.println("host:\t\t" + url.getHost());
System.out.println("path:\t\t" + url.getPath());
System.out.println("protocol:\t" + url.getProtocol());
System.out.println("query:\t\t" + url.getQuery());
System.out.println("ref:\t\t" + url.getRef());
System.out.println("userinfo:\t" + url.getUserInfo());
System.out.println("\n\n-------------------- get the content --------------------");
BufferedReader reader = null;
try {
String line = "";
reader = new BufferedReader(new InputStreamReader(url.openStream()));
while((line = reader.readLine()) != null){
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
if(reader != null){
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
结果:
httpStr: http://www.baidu.com/s?wd=Java
authority: www.baidu.com
content: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@157f0dc
port: 80
file: /s?wd=Java
host: www.baidu.com
path: /s
protocol: http
query: wd=Java
ref: null
userinfo: null
-------------------- get the content --------------------
<!DOCTYPE html><!--STATUS OK--><html><head>
<meta http-equiv="X-UA-Compatible" content="IE=7">
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<title>百度搜索_Java </title>
<style>
body,td,.p1,.p2,.i{font-family:arial}
body{margin:0;padding:6px 0 0 0;background-color:#fff;color:#000;position:relative}
input{padding-top:0;padding-bottom:0;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box;}
table{border:0}
...
(内容很多,省略。。)
2. Socket通信(以简单的通信为例)
服务器端将客户端输入的信息以大写的形式返给客户端。
package com.java.net;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void echo(){
Socket socket = null;
try {
socket = new Socket("localhost",4444);
Scanner fromServer = new Scanner(socket.getInputStream());
System.out.println(fromServer.nextLine());//打印服务器给用户的提示信息
PrintStream toServer = new PrintStream(socket.getOutputStream(), true);
Scanner in = new Scanner(System.in);
while(in.hasNextLine()){
String input = in.nextLine();
toServer.println(input);
String output = fromServer.nextLine();
System.out.println(output);
if(output.toLowerCase().equals("bye")){
System.out.println("\nNow is disconnected from server...");
break;
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(socket != null){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
echo();
}
}
package com.java.net;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void waitForConnect(){
System.out.println("---- The server is waiting for the clients to connect ----");
ServerSocket server = null;
try {
server = new ServerSocket(4444);
Socket client = server.accept();
System.out.println("Connected to one client ...");
PrintWriter toClient = new PrintWriter(client.getOutputStream(),true);
toClient.println("---- type quit or exit to disconnect to the server ----");
Scanner fromClient = new Scanner(client.getInputStream());
while(fromClient.hasNextLine()){
String line = fromClient.nextLine();
if(line.toLowerCase().equals("quit") || line.toLowerCase().equals("exit")){
toClient.println("Bye");
System.out.println("Disconnected to one client.");
break;
}
toClient.println(line.toUpperCase());
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(server != null){
server.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
waitForConnect();
}
}
输出结果:
客户端:
---- type quit or exit to disconnect to the server ----
hello server
HELLO SERVER
i am hanyuanbo
I AM HANYUANBO
exit
Bye
Now is disconnected from server...
服务器端:
---- The server is waiting for the clients to connect ----
Connected to one client ...
Disconnected to one client.
运行以及显示过程:
(1). 服务器短开启程序。 这样在服务器端会有---- The server is waiting for the clients to connect ----的显示。
(2). 客户端开启程序。 这样在客户端会有---- type quit or exit to disconnect to the server ----的显示。同时服务器端会有Connected to one client ... 的显示。
(3). 当客户端输入数据的时候,同时会显示输入信息的大写形式从服务器端返回。这是服务器端没有任何显示。
(4). 当客户端输入exit的时候,客户端会有Bye的显示,同时会显示Now is disconnected from server...。在服务器端也会有Disconnected to one client.的显示。
3. 关于net中的DatagramSocket 和 DatagramPacket对于UDP的支持。
以下面简短的例子来说明。主要是用到了socket 中的send 和 receive方法。
package com.java.net;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
public class _Client {
static final int size = 256;
public static void echo(){
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
byte[] buf = new byte[size];
InetAddress address = InetAddress.getLocalHost();
send(socket, buf, buf.length, address, 4444);
String initMsg = receive(socket, buf, buf.length);//
System.out.println(initMsg);
Scanner cin = new Scanner(System.in);
while(cin.hasNextLine()){
String str = cin.nextLine();
if(!str.toLowerCase().equals("exit") && !str.toLowerCase().equals("quit")){
buf = new byte[size];
buf = str.getBytes();
send(socket, buf, buf.length, address, 4444);
String received = receive(socket, buf, buf.length);
System.out.println(received);
}else{
break;
}
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} finally{
socket.close();
}
}
public static String receive(DatagramSocket socket, byte[] buf, int length){
String message = null;
DatagramPacket packet = new DatagramPacket(buf, length);
try {
socket.receive(packet);
message = new String(packet.getData(),0,packet.getLength());
} catch (IOException e) {
e.printStackTrace();
}
return message;
}
public static void send(DatagramSocket socket, byte[] buf, int length, InetAddress address, int port){
DatagramPacket packet = new DatagramPacket(buf, length, address, port);//用于发送数据包到指定主机的指定端口
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
echo();
}
}
package com.java.net;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class _Server {
static final int size = 256;
public static void waiting(){
System.out.println("---- The Server is running ----");
String initMsg = "Enter quit or exit to stop";
DatagramSocket socket = null;
byte[] buf = new byte[size];
try {
socket = new DatagramSocket(4444);
DatagramPacket packet = new DatagramPacket(buf, buf.length);//用于接收数据包
socket.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
buf = initMsg.getBytes();//将字符串信息转换成byte数组
send(socket, buf, buf.length, address, port);//发送初始提示信息给客户端
for(;;){
buf = new byte[size];//重新声明缓存
packet = new DatagramPacket(buf,buf.length);
socket.receive(packet);
String fromClient = new String(packet.getData(),0,packet.getLength());
System.out.println(fromClient);
String toClient = fromClient.toUpperCase();
buf = toClient.getBytes();
send(socket, buf, buf.length, address, port);
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(socket != null){
socket.close();
}
}
}
public static void send(DatagramSocket socket, byte[] buf, int length, InetAddress address, int port){
DatagramPacket packet = new DatagramPacket(buf, length, address, port);//用于发送数据包到指定主机的指定端口
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
waiting();
}
}
结果:
(客户端)
Enter quit or exit to stop
nihao
NIHAO
hello
HELLO
hanyuanbo
HANYUANBO
quit
(服务器端)
---- The Server is running ----
nihao
hello
hanyuanbo
运行过程:
(1) 运行server程序,程序会打印出---- The Server is running ----。
(2) 运行client程序,程序会打印出Enter quit or exit to stop。
(3) 每当用户敲入内容,在客户端会返回大写,而在服务器端会显示用户的输入内容。
(4) 当用户输入quit(或者exit)时,客户端退出。
4.
5.
6.
7.
8.
9.
10.