Java笔记(九)
网络编程:
UDP传输:
(UdpSend发送端)通过UDP传输方式,将一段文字数据发送出去:
(1)建立udpsocket服务
(2)提供数据,并将数据封装到数据包中
(3)通过socket服务的发送功能,将数据包发送出去
(4)关闭资源
(UdpReceive接收端)定义一个应用程序,用于接收udp协议传输的数据并处理:
(1)定义udpsocket服务。通常会监听一个端口,其实就是给这个接收网络应用程序定义数字标识,方便于明确哪些数据过来该应用程序可以处理。
(2)定义一个数据包,因为要存储到接收的字节数据,数据包对象中有更多功能可以提取字节数据中不同数据信息
(3)通过socket服务的receive方法将收到的数据存入已定义好的数据包中
(4)通过数据包对象的特有功能,将这些不同的数据取出,打印在控制台上
(5)关闭资源
1 import java.net.DatagramPacket; 2 import java.net.DatagramSocket; 3 import java.net.InetAddress; 4 5 public class UdpSend{ 6 public static void main(String[] args) throws Exception { 7 //创建udp服务,通过DatagramScoket对象 8 DatagramSocket ds = new DatagramSocket(888); 9 10 //确定数据,并封装成数据包。DatagramPacket(byte[] buf, int length, InetAddress address, int port) 11 byte[] buf = "udp!~".getBytes(); 12 DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.0.105"), 10000); 13 14 //通过socket服务,将已有的数据包发送出去。通过send方法 15 ds.send(dp); 16 17 //关闭资源 18 ds.close(); 19 } 20 }
1 import java.net.DatagramPacket; 2 import java.net.DatagramSocket; 3 4 5 public class UdpReceive { 6 public static void main(String[] args) throws Exception { 7 //创建udpsocket服务,建立端点 8 DatagramSocket ds = new DatagramSocket(10000); 9 10 //定义数据包,用于存储数据 11 byte[] buf = new byte[1024]; 12 DatagramPacket dp = new DatagramPacket(buf, buf.length); 13 14 //通过服务的receive方法,将收到的数据存入数据包中 15 ds.receive(dp); 16 17 //通过数据包的方法获取其中的数据 18 String ip = dp.getAddress().getHostAddress(); 19 String data = new String(dp.getData(), 0, dp.getLength()); 20 int port = dp.getPort(); 21 System.out.println(ip + "..." + data + "..." + port); 22 23 //关闭资源 24 ds.close(); 25 } 26 }
键盘录入方式传输数据:
1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 import java.net.DatagramPacket; 4 import java.net.DatagramSocket; 5 import java.net.InetAddress; 6 7 public class UdpSend{ 8 public static void main(String[] args) throws Exception { 9 DatagramSocket ds = new DatagramSocket(888); 10 BufferedReader bufr = 11 new BufferedReader(new InputStreamReader(System.in)); 12 String line = null; 13 while((line = bufr.readLine()) != null){ 14 if("886".equals(line)) 15 break; 16 byte[] buf = line.getBytes(); 17 DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.0.105"), 10001); 18 ds.send(dp); 19 } 20 ds.close(); 21 } 22 }
1 import java.net.DatagramPacket; 2 import java.net.DatagramSocket; 3 4 public class UdpReceive { 5 public static void main(String[] args) throws Exception { 6 DatagramSocket ds = new DatagramSocket(10001); 7 while(true){ 8 byte[] buf = new byte[1024]; 9 DatagramPacket dp = new DatagramPacket(buf, buf.length); 10 ds.receive(dp); 11 String ip = dp.getAddress().getHostAddress(); 12 String data = new String(dp.getData(), 0, dp.getLength()); 13 int port = dp.getPort(); 14 System.out.println(ip + ":" + port + ": " + data); 15 } 16 } 17 }
一个聊天程序:
1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 import java.net.DatagramPacket; 4 import java.net.DatagramSocket; 5 import java.net.InetAddress; 6 7 class Send implements Runnable{ 8 private DatagramSocket ds; 9 Send(DatagramSocket ds){ 10 this.ds = ds; 11 } 12 public void run(){ 13 try{ 14 BufferedReader bufr = 15 new BufferedReader(new InputStreamReader(System.in)); 16 String line = null; 17 while((line = bufr.readLine()) != null){ 18 if("886".equals(line)) 19 break; 20 byte[] buf = line.getBytes(); 21 DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.0.105"), 10002); 22 ds.send(dp); 23 } 24 }catch(Exception e){ 25 throw new RuntimeException("发送端失败!"); 26 } 27 } 28 } 29 30 public class UdpSend{ 31 public static void main(String[] args) throws Exception { 32 DatagramSocket ds = new DatagramSocket(8888); 33 new Thread(new Send(ds)).start(); 34 } 35 }
1 import java.net.DatagramPacket; 2 import java.net.DatagramSocket; 3 4 class Receive implements Runnable{ 5 private DatagramSocket ds; 6 Receive(DatagramSocket ds){ 7 this.ds = ds; 8 } 9 public void run(){ 10 try{ 11 while(true){ 12 byte[] buf = new byte[1024]; 13 DatagramPacket dp = new DatagramPacket(buf, buf.length); 14 ds.receive(dp); 15 String ip = dp.getAddress().getHostAddress(); 16 String data = new String(dp.getData(), 0, dp.getLength()); 17 System.out.println(ip + ": " + data); 18 } 19 }catch(Exception e){ 20 throw new RuntimeException("接收端失败!"); 21 } 22 } 23 } 24 25 public class UdpReceive{ 26 public static void main(String[] args) throws Exception{ 27 DatagramSocket ds = new DatagramSocket(10002); 28 new Thread(new Receive(ds)).start(); 29 } 30 }
TCP传输:
(1)分客户端和服务端
(2)客户端对应的对象时Socket,服务端对应的对象是ServerSocket
客户端:在该对象建立时,就可以连接指定主机,因为TCP是面向连接的。所以在建立Socket服务时,就要有服务端存在,并连接成功。形成通路后,在该通道进行数据传输。
1 import java.io.OutputStream; 2 import java.net.Socket; 3 4 public class Client{ 5 public static void main(String[] args) throws Exception{ 6 //创建客户端的Socket服务,指定目的主机和端口 7 Socket s = new Socket("192.168.0.105", 10003); 8 9 //为了发送数据,应该获取Socket流中的输出流 10 OutputStream out = s.getOutputStream(); 11 12 out.write("I'm coming!".getBytes()); 13 14 s.close(); 15 } 16 }
1 import java.io.InputStream; 2 import java.net.ServerSocket; 3 import java.net.Socket; 4 5 public class Server{ 6 public static void main(String[] args) throws Exception{ 7 //建立服务端的Socket服务,并监听一个端口 8 ServerSocket ss = new ServerSocket(10003); 9 10 //通过accept方法获取连接过来的客户端对象 11 Socket s = ss.accept(); 12 String ip = s.getInetAddress().getHostAddress(); 13 System.out.println(ip + "...connected"); 14 15 //获取客户端发送过来的数据,要使用客户端对象的读取流来读取数据 16 InputStream in = s.getInputStream(); 17 18 byte[] buf = new byte[1024]; 19 int len = in.read(buf); 20 System.out.println(new String(buf, 0, len)); 21 22 s.close(); 23 ss.close(); 24 } 25 }
tcp传输的客户端和服务端的互访:
客户端给服务端发送数据,服务端收到后,给客户端反馈信息。
1 import java.io.InputStream; 2 import java.io.OutputStream; 3 import java.net.Socket; 4 5 public class Client{ 6 public static void main(String[] args) throws Exception { 7 Socket s = new Socket("192.168.0.105", 10004); 8 OutputStream out = s.getOutputStream(); 9 out.write("你好啊!~".getBytes()); 10 InputStream in = s.getInputStream(); 11 byte[] buf = new byte[1024]; 12 int len = in.read(buf); 13 System.out.println(new String(buf, 0, len)); 14 s.close(); 15 } 16 }
1 import java.io.InputStream; 2 import java.io.OutputStream; 3 import java.net.ServerSocket; 4 import java.net.Socket; 5 6 public class Server{ 7 public static void main(String[] args) throws Exception{ 8 ServerSocket ss = new ServerSocket(10004); 9 Socket s = ss.accept(); 10 System.out.println(s.getInetAddress().getHostName() + "...connected!"); 11 InputStream in = s.getInputStream(); 12 byte[] buf = new byte[1024]; 13 int len = in.read(buf); 14 System.out.println(new String(buf, 0, len)); 15 OutputStream out = s.getOutputStream(); 16 out.write("你也好啊".getBytes()); 17 s.close(); 18 ss.close(); 19 } 20 }
建立一个文本转换服务器,客户端给服务端发送文本,服务端会将文本转换成大写再返回给客户端,而且客户端可以不断地进行文本转换,当客户端输入over时,转换结束:
1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.InputStreamReader; 4 import java.io.OutputStreamWriter; 5 import java.net.Socket; 6 7 public class Client{ 8 public static void main(String[] args) throws Exception{ 9 Socket s = new Socket("192.168.0.105", 10005); 10 11 //读取键盘数据的流对象 12 BufferedReader bufr = 13 new BufferedReader(new InputStreamReader(System.in)); 14 15 //将数据写入到socket输出流 16 BufferedWriter bufout = 17 new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); 18 19 //读取服务端返回的信息 20 BufferedReader bufin = 21 new BufferedReader(new InputStreamReader(s.getInputStream())); 22 23 String line = null; 24 while((line = bufr.readLine()) != null){ 25 if("over".equals(line)) 26 break; 27 //此处要添加结束标记,否则服务端会一直等待。服务端同理 28 bufout.write(line); 29 bufout.newLine(); 30 bufout.flush(); 31 String str = bufin.readLine(); 32 System.out.println("Server: " + str); 33 } 34 35 bufr.close(); 36 s.close(); 37 } 38 }
1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.InputStreamReader; 4 import java.io.OutputStreamWriter; 5 import java.net.ServerSocket; 6 import java.net.Socket; 7 8 public class Server{ 9 public static void main(String[] args) throws Exception{ 10 ServerSocket ss = new ServerSocket(10005); 11 Socket s = ss.accept(); 12 System.out.println(s.getInetAddress().getHostName() + "...Connected!"); 13 14 BufferedReader bufr = 15 new BufferedReader(new InputStreamReader(s.getInputStream())); 16 BufferedWriter bufw = 17 new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); 18 String line = null; 19 while((line = bufr.readLine()) != null){ 20 bufw.write(line.toUpperCase()); 21 bufw.newLine(); 22 bufw.flush(); 23 } 24 } 25 }
tcp复制文件:
1 import java.io.BufferedReader; 2 import java.io.FileReader; 3 import java.io.InputStreamReader; 4 import java.io.PrintWriter; 5 import java.net.Socket; 6 7 public class Client{ 8 public static void main(String[] args) throws Exception{ 9 Socket s = new Socket("192.168.0.105", 10006); 10 BufferedReader bufr = 11 new BufferedReader(new FileReader("F:\\demo.txt")); 12 PrintWriter out = new PrintWriter(s.getOutputStream(), true); 13 String line = null; 14 while((line = bufr.readLine()) != null){ 15 out.println(line); 16 } 17 18 //关闭客户端输出流,相当于给流中加入结束标记 19 s.shutdownOutput(); 20 21 BufferedReader bufIn = 22 new BufferedReader(new InputStreamReader(s.getInputStream())); 23 String str = bufIn.readLine(); 24 System.out.println(str); 25 26 bufr.close(); 27 } 28 }
1 import java.io.BufferedReader; 2 import java.io.FileWriter; 3 import java.io.InputStreamReader; 4 import java.io.PrintWriter; 5 import java.net.ServerSocket; 6 import java.net.Socket; 7 8 public class Server{ 9 public static void main(String[] args) throws Exception{ 10 ServerSocket ss = new ServerSocket(10006); 11 Socket s = ss.accept(); 12 13 BufferedReader bufIn = 14 new BufferedReader(new InputStreamReader(s.getInputStream())); 15 PrintWriter out = new PrintWriter(new FileWriter("F:\\demo2.txt"), true); 16 String line = null; 17 while((line = bufIn.readLine()) != null){ 18 out.println(line); 19 } 20 21 PrintWriter pw = new PrintWriter(s.getOutputStream(), true); 22 pw.println("上传成功"); 23 } 24 }
上传图片:
1 import java.io.FileInputStream; 2 import java.io.InputStream; 3 import java.io.OutputStream; 4 import java.net.Socket; 5 6 public class Client{ 7 public static void main(String[] args) throws Exception{ 8 Socket s = new Socket("192.168.0.105", 10007); 9 FileInputStream fis = new FileInputStream("F:\\1.jpg"); 10 OutputStream out = s.getOutputStream(); 11 byte[] buf = new byte[1024]; 12 int len = 0; 13 while((len = fis.read(buf)) != -1){ 14 out.write(buf, 0, len); 15 } 16 17 //通知服务端数据已经写完 18 s.shutdownOutput(); 19 InputStream in = s.getInputStream(); 20 byte[] bufIn = new byte[1024]; 21 int num = in.read(bufIn); 22 System.out.println(new String(bufIn, 0, num)); 23 24 fis.close(); 25 s.close(); 26 } 27 }
import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Server{ public static void main(String[] args) throws Exception{ ServerSocket ss = new ServerSocket(10007); Socket s = ss.accept(); System.out.println(s.getInetAddress().getHostName() + "...Connected"); InputStream in = s.getInputStream(); FileOutputStream fos = new FileOutputStream("F:\\2.jpg"); 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(); ss.close(); s.close(); } }
客户端并发上传图片:
为了让多个客户端可以同时访问服务端,最好就是将每个客户端封装到一个单独的线程中,这样就可以同时处理多个客户端请求。
1 import java.io.File; 2 import java.io.FileOutputStream; 3 import java.io.InputStream; 4 import java.io.OutputStream; 5 import java.net.Socket; 6 7 class PicThread implements Runnable{ 8 private Socket s; 9 PicThread(Socket s){ 10 this.s = s; 11 } 12 public void run(){ 13 int count = 1; 14 String ip = s.getInetAddress().getHostAddress(); 15 try{ 16 System.out.println(ip + "..Connected"); 17 18 InputStream in = s.getInputStream(); 19 20 //用客户端的IP命名文件,若重复,则在文件名后添加(1)。。。 21 File file = new File("F:\\" + ip + ".jpg"); 22 while(file.exists()) 23 file = new File("F:\\" + ip + "(" + (count++) + ")" + ".jpg"); 24 25 FileOutputStream fos = new FileOutputStream(file); 26 byte[] buf = new byte[1024]; 27 int len = 0; 28 while((len = in.read(buf)) != -1){ 29 fos.write(buf, 0, len); 30 } 31 OutputStream out = s.getOutputStream(); 32 out.write("上传成功!".getBytes()); 33 fos.close(); 34 s.close(); 35 36 }catch(Exception e){ 37 throw new RuntimeException(ip + "上传失败!"); 38 } 39 } 40 }
1 import java.io.FileInputStream; 2 import java.io.InputStream; 3 import java.io.OutputStream; 4 import java.net.Socket; 5 6 public class Client{ 7 public static void main(String[] args) throws Exception{ 8 Socket s = new Socket("192.168.0.105", 10007); 9 FileInputStream fis = new FileInputStream("F:\\1.jpg"); 10 OutputStream out = s.getOutputStream(); 11 byte[] buf = new byte[1024]; 12 int len = 0; 13 while((len = fis.read(buf)) != -1){ 14 out.write(buf, 0, len); 15 } 16 17 //通知服务端数据已经写完 18 s.shutdownOutput(); 19 InputStream in = s.getInputStream(); 20 byte[] bufIn = new byte[1024]; 21 int num = in.read(bufIn); 22 System.out.println(new String(bufIn, 0, num)); 23 24 fis.close(); 25 s.close(); 26 } 27 }
1 import java.net.ServerSocket; 2 import java.net.Socket; 3 4 public class Server{ 5 public static void main(String[] args) throws Exception{ 6 ServerSocket ss = new ServerSocket(10007); 7 while(true){ 8 Socket s = ss.accept(); 9 new Thread(new PicThread(s)).start(); 10 } 11 //ss.close(); 12 } 13 }
客户端通过键盘录入用户名,服务端对这个用户名进行校验。
如果该用户存在,在服务端显示XXX,已登录。并在客户端显示XXX,欢迎光临。
如果该用户不存在,在服务端显示XXX,尝试登录。并在客户端显示XXX,该用户不存在。
最多登录三次:
1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 import java.io.PrintWriter; 4 import java.net.Socket; 5 6 public class Client{ 7 public static void main(String[] args) throws Exception{ 8 Socket s = new Socket("192.168.0.105", 10008); 9 BufferedReader bufr = 10 new BufferedReader(new InputStreamReader(System.in)); 11 PrintWriter out = new PrintWriter(s.getOutputStream(), true); 12 BufferedReader bufIn = 13 new BufferedReader(new InputStreamReader(s.getInputStream())); 14 15 for(int i = 0; i < 3; i++){ 16 String line = bufr.readLine(); 17 if(line == null) 18 break; 19 20 out.println(line); 21 22 String info = bufIn.readLine(); 23 System.out.println(info); 24 25 //传回客户端的信息中包含“欢迎光临”字样,则不用继续登录,可以跳出循环 26 if(info.contains("欢迎光临")) 27 break; 28 29 } 30 bufr.close(); 31 s.close(); 32 } 33 }
1 import java.net.ServerSocket; 2 import java.net.Socket; 3 4 public class Server{ 5 public static void main(String[] args) throws Exception{ 6 ServerSocket ss = new ServerSocket(10008); 7 while(true){ 8 Socket s = ss.accept(); 9 new Thread(new UserThread(s)).start(); 10 } 11 } 12 }
1 import java.io.BufferedReader; 2 import java.io.FileReader; 3 import java.io.InputStreamReader; 4 import java.io.PrintWriter; 5 import java.net.Socket; 6 7 public class UserThread implements Runnable { 8 private Socket s; 9 UserThread(Socket s){ 10 this.s = s; 11 } 12 public void run() { 13 String ip = s.getInetAddress().getHostAddress(); 14 System.out.println(ip + "...Connected"); 15 try{ 16 for(int i = 0; i < 3; i++){ 17 BufferedReader bufIn = 18 new BufferedReader(new InputStreamReader(s.getInputStream())); 19 String name = bufIn.readLine(); 20 if(name == null) 21 break; 22 23 BufferedReader bufr = 24 new BufferedReader(new FileReader("F:\\user.txt")); 25 PrintWriter pw = new PrintWriter(s.getOutputStream(), true); 26 String line = null; 27 boolean flag = false; 28 while((line = bufr.readLine()) != null){ 29 if(line.equals(name)){ 30 flag = true; 31 break; 32 } 33 } 34 if(flag){ 35 System.out.println(name + ",已登录"); 36 pw.println(name + ",欢迎光临"); 37 break; 38 } 39 else{ 40 System.out.println(name + ",尝试登陆"); 41 pw.println(name + ",该用户不存在"); 42 } 43 } 44 s.close(); 45 }catch(Exception e){ 46 throw new RuntimeException("校验失败"); 47 } 48 } 49 50 }