Java笔记(二十九)……网络编程
概述
网络模型
网络通讯的要素
ip地址:网络中设备的标识符
端口:用于标识同一台设备上不同的进程,有效端口:0~65535,其中0~1024是系统使用端口或者保留端口
TCP与UDP
UDP特点:
面向无连接,速度快,不可靠
数据包中封装了数据、源和目的
每个数据报最大为64K
TCP特点:
面向连接,通过三次握手建立连接,安全可靠
经常用于大数据的传输
Socket套接字
Socket就是为网络服务提供的一种机制
通信的两端都有Socket
网络通信其实就是Socket间的通信
数据在两个Socket间通过IO传输
UDP传输
DatagramSocket:UDP套接字
DatagramPacket:UDP数据报
下面是UDP实现的简单传输
1: import java.net.*;
2: import java.io.*;
3:
4: /*
5: 服务器读取键盘的数据,变成大写发送给客户端
6: */
7:
8: class UdpServerDemo
9: {
10: public static void main(String[] args) throws Exception
11: {
12: //建立udp服务
13: DatagramSocket ds = new DatagramSocket();
14:
15: //建立键盘输入流
16: BufferedReader bufr =
17: new BufferedReader(new InputStreamReader(System.in));
18:
19: String line = null;
20:
21: while( (line = bufr.readLine()) != null)
22: {
23: //定义数据包
24: byte[] data = line.toUpperCase().getBytes();
25: InetAddress ia = InetAddress.getLocalHost();
26: int port = 10000;
27: DatagramPacket dp = new DatagramPacket(data,data.length,ia,port);
28:
29: //发送数据包
30: ds.send(dp);
31: }
32:
33: //关闭资源
34: //ds.close();
35:
36: }
37: }
38:
39: class UdpClientDemo
40: {
41: public static void main(String[] args) throws Exception
42: {
43: //建立UDP服务
44: DatagramSocket ds = new DatagramSocket(10000);
45:
46: //定义接收数据包
47: byte[] data = new byte[1024];
48: DatagramPacket dp = new DatagramPacket(data,1024);
49:
50: while(true)
51: {
52: //接收数据包
53: ds.receive(dp);
54:
55: //打印相关信息
56: System.out.println("Address:"+dp.getAddress().getHostAddress()+"---port:"+dp.getPort());
57: System.out.println(new String(dp.getData(),0,dp.getLength()));
58: }
59:
60: //关闭资源
61: //ds.close();
62:
63: }
64: }
TCP传输
ServerSocket:服务端套接字
Socket:客户端套接字
下面是用tcp实现的简单上传图片功能
1: import java.io.*;
2: import java.net.*;
3:
4: class UploadPicClient
5: {
6: public static void main(String[] args) throws Exception
7: {
8: //建立客户端TCP服务
9: InetAddress ia = InetAddress.getLocalHost();
10: Socket s = new Socket(ia,10000);
11:
12: //建立本地文件字节流
13: BufferedInputStream bufi = new BufferedInputStream(new FileInputStream("1.jpeg"));
14:
15: //建立tcp输出流
16: BufferedOutputStream bufo = new BufferedOutputStream(s.getOutputStream());
17:
18: //读取本地文件,通过tcp输出流传输到服务器
19: int len = -1;
20: byte[] data = new byte[1024];
21:
22: while( (len = bufi.read(data)) != -1 )
23: {
24: bufo.write(data,0,len);
25: bufo.flush();
26: }
27:
28: //关闭tcp输出流,相当于为服务器发送了一个结束标记 :-1
29: s.shutdownOutput();
30:
31: //建立tcp输入流
32: BufferedReader bufr =
33: new BufferedReader(new InputStreamReader(s.getInputStream()));
34:
35: //打印读取到的确认信息
36: System.out.println(bufr.readLine());
37:
38: //关闭资源
39: s.close();
40: }
41: }
42:
43: class UploadPicServer
44: {
45: public static void main(String[] args) throws Exception
46: {
47: //建立服务器tcp服务
48: ServerSocket ss = new ServerSocket(10000);
49:
50: //等待客户端连接
51: Socket s = ss.accept();
52:
53: //打印客户机ip信息
54: System.out.println(s.getInetAddress().getHostName()+" connecting...");
55:
56: //建立tcp读取流
57: BufferedInputStream bufi = new BufferedInputStream(s.getInputStream());
58:
59: //为本地文件建立输入流
60: BufferedOutputStream bufo = new BufferedOutputStream(new FileOutputStream("pic.jpeg"));
61:
62: //读取网络数据,写入到本地文件
63: int len = -1;
64: byte[] data = new byte[1024];
65:
66: while( (len = bufi.read(data)) != -1)
67: {
68: bufo.write(data,0,len);
69: bufo.flush();
70: }
71:
72: //建立tcp输出流
73: PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
74:
75: //发送服务器确认信息
76: pw.println("上传成功");
77:
78: //关闭资源
79: s.close();
80: ss.close();
81: }
82: }
URL-URLConnection
URL:
Uniform Resource Locator,俗称网页地址
String getFile()
获取此 URL 的文件名。
String getHost()
获取此 URL 的主机名(如果适用)。
String getPath()
获取此 URL 的路径部分。
int getPort()
获取此 URL 的端口号。
String getProtocol()
获取此 URL 的协议名称。
String getQuery()
获取此 URL 的查询部
URLConnection openConnection()
返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。
URLConnection
URLConnection内部已经封装好了网络读写流,直接调用方法获取即可
InputStream getInputStream()
返回从此打开的连接读取的输入流。
OutputStream getOutputStream()
返回写入到此连接的输出流。
下面是URL实现的简单的浏览器,暂时没有调用HTML解析引擎,所以读到的数据都是带标签的html代码
1: import java.awt.*;
2: import java.awt.event.*;
3: import java.io.*;
4: import java.net.*;
5:
6: class MyWindow
7: {
8: private Frame f;
9: private TextField tf;
10: private TextArea ta;
11: private Button b;
12: private Dialog dErrorUrl;
13: private Label lErrorUrl;
14: private Button bErrorUrl;
15:
16: MyWindow()
17: {
18: init();
19: }
20:
21: //初始化窗口
22: private void init()
23: {
24: f = new Frame();
25: f.setTitle("我的浏览器");
26: f.setBounds(200,200,800,600);
27:
28: tf = new TextField(100);
29: ta = new TextArea(30,110);
30: b = new Button("转到");
31:
32: f.setLayout(new FlowLayout());
33:
34: f.add(tf);
35: f.add(b);
36: f.add(ta);
37:
38: dErrorUrl = new Dialog(f,"Error Url!",true);
39: dErrorUrl.setBounds(300,300,240,90);
40: dErrorUrl.setLayout(new FlowLayout());
41: lErrorUrl = new Label();
42: bErrorUrl = new Button("Ok");
43:
44: dErrorUrl.add(lErrorUrl);
45: dErrorUrl.add(bErrorUrl);
46:
47: action();
48:
49: f.setVisible(true);
50: }
51:
52: //一些简单事件响应
53: private void action()
54: {
55: //窗口关闭动作
56: f.addWindowListener(new WindowAdapter()
57: {
58: public void windowClosing(WindowEvent e)
59: {
60: System.exit(0);
61: }
62: });
63:
64: //URL输入动作
65: tf.addKeyListener(new KeyAdapter()
66: {
67: public void keyPressed(KeyEvent e)
68: {
69: if(e.getKeyCode() == KeyEvent.VK_ENTER)
70: toUrl();
71:
72: //ta.setText(tf.getText());
73: }
74: });
75:
76: b.addActionListener(new ActionListener()
77: {
78: public void actionPerformed(ActionEvent e)
79: {
80: toUrl();
81: }
82: });
83:
84: bErrorUrl.addActionListener(new ActionListener()
85: {
86: public void actionPerformed(ActionEvent e)
87: {
88: dErrorUrl.setVisible(false);
89: }
90: });
91:
92: dErrorUrl.addWindowListener(new WindowAdapter()
93: {
94: public void windowClosing(WindowEvent e)
95: {
96: dErrorUrl.setVisible(false);
97: }
98: });
99:
100: }
101:
102: //打开网站
103: private void toUrl()
104: {
105: URL url = null;
106: try
107: {
108: //获取文本框中的url
109: url = new URL(tf.getText());
110: }
111: catch (Exception e)
112: {
113: lErrorUrl.setText(e.toString());
114: dErrorUrl.setVisible(true);
115: }
116:
117: if(url != null)
118: {
119: ta.setText("");
120:
121: try
122: {
123: //创建URL连接
124: URLConnection conn = url.openConnection();
125: //获取输入流
126: BufferedInputStream bufr = new BufferedInputStream(conn.getInputStream());
127:
128: //读取网站服务器返回的数据
129: byte[] buf = new byte[1024];
130: int len = -1;
131:
132: while( (len= bufr.read(buf)) != -1)
133: {
134: //打印到文本区域
135: ta.append(new String(buf,0,len));
136: }
137:
138: //打开本地浏览器
139: //Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+url);
140: }
141: catch (IOException e)
142: {
143: lErrorUrl.setText(e.toString());
144: dErrorUrl.setVisible(true);
145: }
146: catch (Exception ex)
147: {
148: ta.append("\r\n"+ex.toString()+"\r\n");
149: }
150:
151: }
152:
153: }
154: }
155:
156: class MyBrowserDemo
157: {
158: public static void main(String[] args)
159: {
160: new MyWindow();
161: }
162: }