黑马程序员_网络通讯
来源:互联网 发布:ucloud 阿里云 编辑:程序博客网 时间:2024/06/04 18:52
—————————— ASP.Net+Android+IOS开发、.Net培训、期待与您交流!——————————
UDP
将数据及源和目的封装成数据包中,不需要建立连接
每个数据包的大小限制在64K内
因无连接,是不可靠协议
不需要建立连接,速度快
接收和发送可以使用同一个DatagramSocket(要注意阻塞)
如果是发送,则数据包必需设置地址和端口,如果是接收,则只要设置byte数组缓冲区就可以了
获得对方的地址和端口通过DatagramPacket.getAddress() DatagramPacket.getPort()
发送的数据包封装的是目的地址和端口,接收的数据包封装的是发送方的地址和端口
TCP
建立连接,形成传输数据的通道。
在连接中进行大数据量传输
通过三次握手完成连接,是可靠协议
必需建立连接,效率会稍低
获得对方的地址通过Socket.getInetAddress() Socket.getPort()
/*演示tcp传输
1,tcp分客户端和服务端。
2, 客户端对应的对象是Socket。
服务端对应的对象是ServerSocket。
需求:给服务端发送给一个文本数据。
步骤:
1,创建Socket服务。并指定要连接的主机和端口。
*/
class TcpClient{ public static void main(String[] args) throws Exception { //创建客户端的socket服务。指定目的主机和端口 Socket s = new Socket("192.168.1.254",10003); //为了发送数据,应该获取socket流中的输出流。 OutputStream out = s.getOutputStream(); out.write("tcp ge men lai le ".getBytes()); s.close(); }}
/*
需求:定义端点接收数据并打印在控制台上。
服务端:
1,建立服务端的socket服务。ServerSocket();并监听一个端口。
2,获取连接过来的客户端对象。通过ServerSokcet的 accept方法。没有连接就会等,所以这个方法阻塞式的。
3,客户端如果发过来数据,那么服务端要使用对应的客户端对象,并获取到该客户端对象的读取流来读取发过来的数据。并打印在控制台。
4,关闭服务端。(可选)
*/
class TcpServer{ public static void main(String[] args) throws Exception{ //建立服务端socket服务。并监听一个端口。 ServerSocket ss = new ServerSocket(10003); //通过accept方法获取连接过来的客户端对象。 while(true){ 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();//关闭客户端. } }}
//需求:上传文件。
import java.io.*;import java.net.*;class Client{ public static void main(String[] args) throws Exception{ Socket s = new Socket("192.168.1.254",10006); BufferedReader bufr = new BufferedReader(new FileReader("IPDemo.java")); //定义目的,将数据写入到socket输出流。发给服务端。 //BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); PrintWriter out = new PrintWriter(s.getOutputStream(),true); String line = null; while((line=bufr.readLine())!=null){ out.println(line); } s.shutdownOutput();//关闭客户端的输出流。相当于给流中加入一个结束标记—1. //定义一个socket读取流,读取服务端返回的信息。 BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); String str = bufIn.readLine(); System.out.println(str); bufr.close(); s.close(); }}class Server{ 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"); //读取socket读取流中的数据。 BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); //目的。socket输出流。将大写数据写入到socket输出流,并发送给客户端。 //BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); PrintWriter out = new PrintWriter(new FileWriter("server.txt"),true); String line = null; while((line=bufIn.readLine())!=null){ //if("over".equals(line)) //break; out.println(line); } PrintWriter pw = new PrintWriter(s.getOutputStream(),true); pw.println("上传成功"); out.close(); s.close(); ss.close(); }}
/*需求:上传图片。
客户端。
1,服务端点。
2,读取客户端已有的图片数据。
3,通过socket 输出流将数据发给服务端。
4,读取服务端反馈信息。
5,关闭。*/
import java.io.*;import java.net.*;class PicClient{ public static void main(String[] args)throws Exception { if(args.length!=1){ System.out.println("请选择一个jpg格式的图片"); return ; } File file = new File(args[0]); if(!(file.exists() && file.isFile())){ System.out.println("该文件有问题,要么补存在,要么不是文件"); return ; } if(!file.getName().endsWith(".jpg")){ System.out.println("图片格式错误,请重新选择"); return ; } if(file.length()>1024*1024*5){ System.out.println("文件过大,没安好心"); return ; } Socket s = new Socket("192.168.1.254",10007); FileInputStream fis = new FileInputStream(file); OutputStream out = s.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; while((len=fis.read(buf))!=—1){ out.write(buf,0,len); } //告诉服务端数据已写完 s.shutdownOutput(); InputStream in = s.getInputStream(); byte[] bufIn = new byte[1024]; int num = in.read(bufIn); System.out.println(new String(bufIn,0,num)); fis.close(); s.close(); }}//服务端class PicThread implements Runnable{ private Socket s; PicThread(Socket s){ this.s = s; } public void run(){ int count = 1; String ip = s.getInetAddress().getHostAddress(); try{ System.out.println(ip+"....connected"); InputStream in = s.getInputStream(); File dir = new File("d:\\pic"); File file = new File(dir,ip+"("+(count)+")"+".jpg"); while(file.exists()) file = new File(dir,ip+"("+(count++)+")"+".jpg"); FileOutputStream fos = new FileOutputStream(file); byte[] buf = new byte[1024]; int len = 0; while((len=in.read(buf))!=—1){ fos.write(buf,0,len); } OutputStream out = s.getOutputStream(); out.write("上传成功".getBytes()); fos.close(); s.close(); } catch (Exception e){ throw new RuntimeException(ip+"上传失败"); } }}class PicServer{ public static void main(String[] args) throws Exception{ ServerSocket ss = new ServerSocket(10007); while(true){ Socket s = ss.accept(); new Thread(new PicThread(s)).start(); } //ss.close(); }}
/*
编写一个聊天程序。
有收数据的部分,和发数据的部分。
这两部分需要同时执行。
那就需要用到多线程技术。
一个线程控制收,一个线程控制发。
因为收和发动作是不一致的,所以要定义两个run方法。
而且这两个方法要封装到不同的类中。
*/
import java.io.*;import java.net.*;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){ byte[] buf = line.getBytes(); DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10002); ds.send(dp); if("886".equals(line)) break; } } 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()); if("886".equals(data)){ System.out.println(ip+"....离开聊天室"); break; } System.out.println(ip+":"+data); } } catch (Exception e) { throw new RuntimeException("接收端失败"); } }}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(); }}
/*
需求:通过udp传输方式,将一段文字数据发送出去。
定义一个udp发送端。
思路:
1,建立updsocket服务。
2,提供数据,并将数据封装到数据包中。
3,通过socket服务的发送功能,将数据包发出去。
4,关闭资源。
*/
import java.net.*;class UdpSend{ public static void main(String[] args) throws Exception{ //1,创建udp服务。通过DatagramSocket对象。 DatagramSocket ds = new DatagramSocket(8888); //2,确定数据,并封装成数据包。DatagramPacket(byte[] buf, int length, InetAddress address, int port) byte[] buf = "udp ge men lai le ".getBytes(); DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.254"),10000); //3,通过socket服务,将已有的数据包发送出去。通过send方法。 ds.send(dp); //4,关闭资源。 ds.close(); }}
/*
需求:
定义一个应用程序,用于接收udp协议传输的数据并处理的。
定义udp的接收端。
思路:
1,定义udpsocket服务。通常会监听一个端口。其实就是给这个接收网络应用程序定义数字标识。
方便于明确哪些数据过来该应用程序可以处理。
2,定义一个数据包,因为要存储接收到的字节数据。
因为数据包对象中有更多功能可以提取字节数据中的不同数据信息。
3,通过socket服务的receive方法将收到的数据存入已定义好的数据包中。
4,通过数据包对象的特有功能。将这些不同的数据取出。打印在控制台上。
5,关闭资源。
*/
class UdpRece{ public static void main(String[] args) throws Exception{ //1,创建udp socket,建立端点。 DatagramSocket ds = new DatagramSocket(10000); while(true){ //2,定义数据包。用于存储数据。 byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf,buf.length); //3,通过服务的receive方法将收到数据存入数据包中。 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); } //5,关闭资源 //ds.close(); }}
—————————— ASP.Net+Android+IOS开发、.Net培训、期待与您交流!——————————
0 0
- 黑马程序员_网络通讯
- 黑马程序员--网络通讯
- 黑马程序员___网络通讯
- 黑马程序员 网络通讯
- 黑马程序员java之网络通讯
- 黑马程序员--java基础之网络通讯
- 【黑马程序员】Java基础12:UDP和TCP的网络通讯
- 黑马程序员——网络编程1:网络通讯原理简介
- 黑马程序员————Java网络通讯编程详解
- 黑马程序员_枚举
- 黑马程序员_多线程
- 黑马程序员_反射
- 黑马程序员_泛型
- 黑马程序员_注解
- 黑马程序员_注解
- 黑马程序员_泛型
- 黑马程序员_代理
- 黑马程序员_继承
- cocos2d-x初探学习笔记 -- 触屏事件
- 配置JBoss环境变量
- java备忘录模式
- Hibernate4.2.2搭建Junit日志环境
- express3.0安装并使用layout模板
- 黑马程序员_网络通讯
- CString.Format的详细用法(转)
- java备忘录模式实例
- 九度OJ 1537 买卖股票(DP)
- node.js连接MySQL
- oracle中 connect by prior 递归算法
- Intent详解
- MATLAB2010a+OpenCV2.3.1+VS2010运行TLD
- Linux下源码的卸载与重装