黑马程序员_网络编程(一)

来源:互联网 发布:成都淘宝运营公司 编辑:程序博客网 时间:2024/06/06 01:19

---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ---------------------


概述    网络模型

IP地址

public class IPDemo {public static void main(String[] args) throws Exception {InetAddress i = InetAddress.getLocalHost();System.out.println(i.toString());System.out.println("name="+i.getHostName());System.out.println("address="+i.getHostAddress());InetAddress ia = InetAddress.getByName("www.baidu.com");System.out.println("name="+ia.getHostName());System.out.println("address="+ia.getHostAddress());}}


TCP和UDP

    UDP:
        将数据及源和目的封装在数据包中,不需要建立连接
        每个数据报大小限制在64k内
        因无连接,是不可靠协议
        不需要连接,速度快
    TCP:
        建立连接,形成传输数据的通到
        在连接中进行大量数据传输
        通过三次握手完成连接,是可靠协议
        必须建立连接,效率稍低

Socket

    Socket就是为网络服务提供的一种机制
    通信的两端都有Socket
    网络通信其实就是Socket间的通信
    数据在两个Socket间通过IO传输

Udp-发送端    Udp-接收端

    DatagramSocket与DatagramPacket
    建立发送端,接收端
    建立数据包
    调用Socket的发送接收方法
    关闭Socket

    发送端与接收端是两个独立运行程序

    UdpSend

/*需求:通过udp传输方式,将一段文字数据发送出去1.建立udpsocket服务2.提供数据,并将数据封装到数据包中3.通过socket服务的发送功能,将数据包发送出去4.关闭资源*/public class UdpSend {public static void main(String[] args) throws Exception {//1.创建udp服务,通过DatagramSocket对象DatagramSocket ds = new DatagramSocket();//2.确定数据,并封装成数据包byte[] buf = "udp haha".getBytes();DatagramPacket dp =new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.102"),10000);//3.通过socket服务,将已有的数据包发送出去,通过send方法ds.send(dp);//4.关闭资源ds.close();}}


    UdpRece

/*需求:定义一个应用程序,勇于接受udp传输协议的 数据并处理思路:1.定义socket服务,通常会监听一个端口,其实就是个这个接收网络应用程序定义数字标识2.定义一个数据包,因为要存储接收到的字节数据因为数据包对象中有更多功能可以提取字节数据中的不同信息3.听过socket服务的receive方法将接收到的数据存入已定义好的数据包中4.通过数据包对象的特有功能,将这些不同的数据取出,并打印在控制台上5.关闭资源*/public class UdpRece{public static void main(String[] args) throws Exception {//1.创建udpsocket,建立端点DatagramSocket ds = new DatagramSocket(10000);//2.定义数据包,用于存储数据byte[] buf =new byte[1024];DatagramPacket dp = new DatagramPacket(buf,buf.length);//3.通过服务的received方法将收到的数据存入数据包中ds.receive(dp);//4.通过数据包的方法获取其中的数据String ip = dp.getAddress().getHostAddress();String data = new String(dp.getData(),0,dp.getLength());int port = dp.getPort();System.out.println(ip+"::"+data+"::"+port);//关闭资源ds.close();}}

UDP-键盘录入方式数据

    UdpSend2

public class UdpSend2 {public static void main(String[] args) throws Exception {DatagramSocket ds = new DatagramSocket();BufferedReader bufr =new BufferedReader(new InputStreamReader(System.in));String line = null;while((line=bufr.readLine())!=null){if("886".equals(line))break;byte[] buf = line.getBytes();DatagramPacket dp =new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.102"),10001);ds.send(dp);}ds.close();}}

    UdpRece2

public class UdpRece2 {public static void main(String[] args) throws Exception {DatagramSocket ds = new DatagramSocket(10001);while(true){byte[] buf =new byte[1024];DatagramPacket dp = new DatagramPacket(buf,buf.length);ds.receive(dp);String ip = dp.getAddress().getHostAddress();String data = new String(dp.getData(),0,dp.getLength());System.out.println(ip+"::"+data);}}}

UDP-聊天

/*编写一个聊天程序有发送和接收数据的部分两部分需要同时执行需要多线程技术一个线程控制发送,一个线程控制接收收和发动作不一致,所以要定义两个run方法,畏怯两个run方法要封装到不同的类中*/class Send implements Runnable{private DatagramSocket ds;public Send(DatagramSocket ds){this.ds = ds;}public void run(){try{BufferedReader bufr =new BufferedReader(new InputStreamReader(System.in));String line =null;while((line=bufr.readLine())!=null){if("886".equals(line))break;byte[] buf =line.getBytes();DatagramPacket dp =new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.102"),10002);ds.send(dp);}}catch(Exception e){throw new RuntimeException("发送端失败");}}}class Rece implements Runnable{private DatagramSocket ds;public Rece(DatagramSocket ds){this.ds = ds;}public void run(){try{while(true){byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf,buf.length);ds.receive(dp);String ip = dp.getAddress().getHostAddress();String data = new String(dp.getData(),0,dp.getLength());System.out.println(ip+"::"+data);}}catch(Exception e){throw new RuntimeException("接收端失败");}}}public class ChatDemo {public static void main(String[] args) throws Exception {DatagramSocket sendSocket = new DatagramSocket();DatagramSocket receSocket = new DatagramSocket(10002);new Thread(new Send(sendSocket)).start();new Thread(new Rece(receSocket)).start();}}

TCP传输

    Socket和ServerSocket
    建立客户端和服务端
    建立连接后,通过Socket中的IO流进行数据传输
    关闭Socket

    客户端与服务端是两个独立的应用程序

    查阅socket对象,发现该对象建立时,就可以去连接指定主机
    因为tcp是面向连接的,所以在建立socket服务时,
    就要有服务端存在,并连接成功,形成通路后,在通道内进行数据传输

    TcpServer

/*需求:定义端点接收数据并打印在控制台上1.建立服务端的socket服务,ServerSocket();并监听一个端口2.获取连接过来的客户端对象通过ServerSocket的accept方法,没有连接就会等,所以这个方法是阻塞式的3.客户端如果发过来数据,那么服务端要使用对应的客户端对象,并获取到该客户端对象的读取流读取发送过来的数据,并打印在控制台上4.关闭服务端(可选)*/public class TcpServer {public static void main(String[] args) throws Exception {//建立服务端socket服务,并监听一个端口ServerSocket ss = new ServerSocket(10003);//通过accept方法获取链接过来的客户端对象Socket s = ss.accept();String ip = s.getInetAddress().getHostAddress();System.out.println(ip+"...connected");//获取客户端发送过来的数据,使用客户端对象的读取流来读取数据InputStream in = s.getInputStream();byte[] buf = new byte[1024];int len = in.read(buf);System.out.println(new String(buf,0,len));s.close();//关闭客户端ss.close();}}

    TcpClient

/*需求:给服务端发送一个文本数据*/public class TcpClient {public static void main(String[] args) throws Exception {//创建客户端的socket服务,指定目的主机和端口Socket s = new Socket("192.168.1.102",10003);//为了发送数据,应该获取socket流中的输出流OutputStream out = s.getOutputStream();out.write("tcp hello".getBytes());s.close();}}

TCP传输2

    演示tcp传输客户端和服务端的互访
    需求:客户端给服务端发送数据,服务端收到后,给客户端反馈信息

    TcpClient2

/*1.建立socket服务,指定要连接主机和端口2.获取socket流中的输出流,将数据写到该流中,通过网络发送给服务端3.获取socket流中的输入流,将服务端反馈的数据获取到,并打印4.关闭客户端资源*/public class TcpClient2 {public static void main(String[] args) throws Exception {Socket s = new Socket("192.168.1.102",10004);OutputStream out = s.getOutputStream();out.write("hi,server".getBytes());InputStream in = s.getInputStream();byte[] buf = new byte[1024];int len = in.read(buf);System.out.println(new String(buf,0,len));s.close();}}

    TcpServer2

public class TcpServer2 {public static void main(String[] args) throws Exception {ServerSocket ss = new ServerSocket(10004);Socket s = ss.accept();String ip = s.getInetAddress().getHostAddress();System.out.println(ip+"...connected");InputStream in = s.getInputStream();byte[] buf = new byte[1024];int len = in.read(buf);System.out.println(new String(buf,0,len));OutputStream out = s.getOutputStream();out.write("copy that, hi".getBytes());s.close();ss.close();}}

TCP练习

    需求:建立一个文本转换服务器,客户端给服务器发送文本,服务器将文本转成大写再返回给客户端,畏怯客户可以不断进行文本转换,当客户输入over时,转换结束。
    都是文本数据,使用字符流,提高效率,加入缓冲。

    TransClient

/*分析:操作设备上的数据,使用IO技术,并按照IO的操作规律思考源:键盘录入    目的:网络输出流操作文本数据,使用字符流步骤:1.建立服务2.获取键盘录入3.将数据发送给服务端4.接收服务端返回的大写数据5.关闭资源*/public class TransClient {public static void main(String[] args) throws Exception {Socket s = new Socket("192.168.1.102",10005);//定义读取键盘数据的流对象BufferedReader bufr =new BufferedReader(new InputStreamReader(System.in));//定义目的,将数据写入到socket输出流,发送给服务端//BufferedWriter bufOut =//new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));PrintWriter out = new PrintWriter(s.getOutputStream(),true);//定义一个socket读取流,读取服务端返回的数据BufferedReader bufIn =new BufferedReader(new InputStreamReader(s.getInputStream()));String line = null;while((line=bufr.readLine())!=null){if("over".equals(line))break;//bufOut.write(line);//bufOut.newLine();//bufOut.flush();out.println(line);String str = bufIn.readLine();System.out.println("server:"+str);}bufr.close();s.close();}}

    TransServer

/*源:socket读取流目的:socket输出流都是文本,装饰*/public class TransServer {public static void main(String[] args) throws Exception {ServerSocket ss = new ServerSocket(10005);Socket s = ss.accept();String ip = s.getInetAddress().getHostAddress();System.out.println(ip+"...connected");//读取socket读取流中的数据BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));//将答谢数据写入socket输出流,并发送给客户端//BufferedWriter bufOut = //new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));PrintWriter out = new PrintWriter(s.getOutputStream(),true);String line = null;while((line=bufIn.readLine())!=null){System.out.println(line);//bufOut.write(line.toUpperCase());//bufOut.newLine();//bufOut.flush();out.println(line.toUpperCase());}s.close();ss.close();}}

TCP复制文件

    TextClient

public class TextClient {public static void main(String[] args) throws Exception {Socket s = new Socket("192.168.1.102",10006);BufferedReader bufr = new BufferedReader(new FileReader("1.txt"));PrintWriter out = new PrintWriter(s.getOutputStream(),true);String line = null;while((line=bufr.readLine())!=null){out.println(line);}s.shutdownOutput();  //关闭客户端输出流,相当于给流加入结束标记-1BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));String str = bufIn.readLine();System.out.println(str);bufr.close();s.close();}}

    TextServer

public class TextServer {public static void main(String[] args) throws Exception {ServerSocket ss = new ServerSocket(10006);Socket s = ss.accept();String ip = s.getInetAddress().getHostAddress();System.out.println(ip+"...connected");BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));PrintWriter out = new PrintWriter(new FileWriter("2.txt"));String line = null;while((line=bufIn.readLine())!=null){out.println(line);}PrintWriter pw = new PrintWriter(s.getOutputStream(),true);pw.println("上传成功");out.close();s.close();ss.close();}}







-----------------------ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------

详细请查看:http://edu.csdn.net


0 0
原创粉丝点击