码迷,mamicode.com
首页 > 其他好文 > 详细

黑马程序员——网络编程总结

时间:2015-12-26 15:01:25      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:

                            ------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
什么是网络编程?
网络编程建立在公共协议TCP/IP或者IOS协议的基础上,通过套接字的服务机制实现不同主机的联系。
 
网络编程的通讯要素
IP地址
网络中设备的识别,本地回环地址为127.0.0.1,主机名:localHost
端口号
用于标识不同进程的逻辑地址
传输协议
常用的协议是:UDP和TCP
 
获取主机网络地址对象
InetAddress  inetaddress1 = InetAddress.getByName("www.baidu.com")或者
InetAddress inetaddress2 = InetAddress.getByName("192.168.1.1")
获取主机名
String hostname = inetaddress1.getHostName();
获取主机地址
String hostaddress = inetaddress1.getHostAddress();
 
套接字Socket
Socket是一种服务接口,它提供的服务能够实现数据包的传递
 
UDP协议特点
面向无连接,不可靠协议
数据报大小限制在64k内
传输速度快,容易丢包
TCP协议特点
面向连接,可靠协议,三次握手,建立连接
在连接中可进行大数据的传输
传输安全,速度慢
 
UDP传输
UDP发送数据报步骤:
1:建立DatagramSocket对象服务
DatagramSocket datagramsocket = new DatagramSocket();
2:建立数据报DatagramPacket对象
byte[] a = "hei ma cheng xu yuan".getBytes();
DatagramPacket  datagrampacket  = new DatagramPacket(a,a.length,InetAddress.getByName("192.168.1.1",10000);
3:发送数据包
datagramsocket.send(datagrampacket);
4:关闭Socket
datagramsocket.close();
UDP接收数据步骤
1:建立DatagramSocket对象服务
DatagramSocket datagramsocket = new DatagramSocket(10000);
2:建立数据报DatagramPacket对象
byte[] a = new byte[1024];
DatagramPacket  datagrampacket  = new DatagramPacket(a,a.length);
3:通过Socket服务的receive()方法把接收到的数据封装到已经准备好的数据包中
datagramsocket.receive();
4.通过接收到的数据包提供的方法,获取数据包中各种数据
返回主机对象
InetAddress inetaddress = a.getAddress();
获取主机名
String hostname = inetaddress1.getHostName();
获取主机地址
String hostaddress = inetaddress1.getHostAddress();
返回数据内容
byte[] data  = a.getData();
String b = new String(data,0,data.length());
返回端口号
int port  = a.getPort();
5,关闭Socket流
datagramsocket.close();
 
Tcp传输
Tcp客户端
1:建立套接字服务
Socket socket = new Socket(InetAddress.getByName("192.168.1.1",10000);
2:获取流
OutputStream output = socket.getOutputStream();
3:通过输入流写入数据
byte[] data  = "ke hu duan qing qiu lian jie".getBytes();
int len = output.write(data);
4:关闭流
socket.close();
Tcp服务端
1:建立套接字服务,并监听端口
ServerSocket serversocket = new ServerSocket(10000);
2:获取连接过来的客户端对象
Socket socket = serversockt.accept();
3:获取客户端连接过来的流,并读取相关数据
InputStream  input  = socket .getInputStream();
byte[] data = new byte[1024];
int len = data.read(data);
4.关闭流
serversocket.close();
 
URL
什么是URL
其实就是表示网页地址的字符串
 
建立URL对象
URL url1 = new URL("https://www.baidu.com/");
URL url2 = new URL("https://192.168.1.254:8080/myweb/demo.html");
 
获取URL对象方法
url2.getFile();获取文件名
url2.getHost();获取主机名
url2.getPort();获取端口号
url2.getPath();获取路径
url2.getProtocol();获取协议
url2.getQuery();获取查询部
 
连接到服务端
URLconnection urlconnection = url2.openConnection();
 1 练习
 2 /*
 3  * 编写一个聊天程序,有收数据的部分,有发数据的部分
 4  */
 5 package bolgtest;
 6 import java.io.*;
 7 import java.net.*;
 8 public class UdpTest {
 9  public static void main(String[] args)throws Exception {
10   DatagramSocket datagramsocket1 = new DatagramSocket();
11   DatagramSocket datagramsocket2 = new DatagramSocket(10000);
12  
13   UdpSend send = new UdpSend(datagramsocket1);
14   UdpReceive receive = new UdpReceive(datagramsocket2);
15   Thread thread1 = new Thread(send);
16   Thread thread2 = new Thread(receive);
17   thread1.start();
18   thread2.start();
19  
20  }
21 }
22 class UdpSend implements Runnable{
23  private DatagramSocket datagramsocket = null;
24  UdpSend(DatagramSocket socket){
25   this.datagramsocket = socket;
26  }
27  public void run(){
28   BufferedReader buffer = null;
29    try{
30      buffer = new BufferedReader(new InputStreamReader(System.in));
31     String str = null;
32     while( (str = buffer.readLine())!=null)
33     {
34      if("886".equals(str))
35       break;
36      byte[] data = str.getBytes();
37      DatagramPacket datagrampacket = new DatagramPacket(data,data.length,InetAddress.getByName("192.168.1.255"),10000);
38      datagramsocket.send(datagrampacket);
39     }
40    }catch(Exception e){
41     throw new RuntimeException("出错啦");
42    }
43    finally{
44     try{
45      buffer.close();
46     }catch(Exception e){
47      throw new RuntimeException("出错啦");
48     }
49    }
50 }
51 }
52  
53 class UdpReceive implements Runnable{
54  private DatagramSocket datagramsocket = null;
55  UdpReceive(DatagramSocket socket){
56   this.datagramsocket = socket;
57  }
58  public void run(){
59   BufferedReader buffer = null;
60   while(true){
61    try{
62     byte[] data = new byte[1024];
63     DatagramPacket datagrampacket = new DatagramPacket(data,data.length);
64     datagramsocket.receive(datagrampacket);
65     String str = new String(datagrampacket.getData(),0,datagrampacket.getData().length);
66     String str2 = datagrampacket.getAddress().getHostAddress();
67     System.out.print(str2+":"+str);
68    }catch(Exception e){
69     throw new RuntimeException("出错啦");
70    }
71   }
72    
73    
74    
75   }
76  }
 1 练习
 2 /*
 3  * 把客户端的一个文件传到服务端去,并且在服务端中存储起来
 4  */
 5 package bolgtest;
 6 import java.io.*;
 7 import java.net.*;
 8 public class ClientTest {
 9  public static void main(String[] args) {
10   try{
11    Socket socket = new Socket("192.168.1.101",10000);
12    BufferedWriter buffwriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
13    BufferedReader clientreader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
14    BufferedReader buffread = new BufferedReader(new FileReader("F:\\BaiduYunDownload\\client.txt"));
15    String str =null;
16    while((str = buffread.readLine())!=null){
17     buffwriter.write(str);
18     buffwriter.newLine();
19     buffwriter.flush();
20    }
21    socket.shutdownOutput();
22    String str1 = null;
23    while((str1 = clientreader.readLine())!=null){
24     System.out.println(str1);
25    }
26   }catch(Exception e){
27    System.out.println(e.getMessage());
28   }
29  
30  
31  
32  }
33 }
34 
35 package bolgtest;
36 import java.io.*;
37 import java.net.ServerSocket;
38 import java.net.Socket;
39 public class ServerTest {
40  public static void main(String[] args)throws Exception {
41   ServerSocket server = new ServerSocket(10000);
42   Socket socket = server.accept();
43   BufferedReader buffreader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
44   BufferedWriter buffwriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
45   PrintWriter printwriter = new PrintWriter(new FileWriter("F:\\BaiduYunDownload\\copy.txt"),true);
46   String str = null;
47   while((str = buffreader.readLine())!=null){
48    printwriter.println(str);
49   }
50   buffwriter.write("上传成功");
51   buffwriter.newLine();
52   buffwriter.flush();
53  
54  }
55 }
56 
57 
58 
59 
60 
61 
62 
63 
64   

 

黑马程序员——网络编程总结

标签:

原文地址:http://www.cnblogs.com/yuemingxingxing/p/5078030.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!