//没有封装端口
public static void main(String[] args) throws UnknownHostException{ //使用getLocalHost方法创建InetAddress对象 InetAddress addr = InetAddress.getLocalHost(); System.out.println(addr.getHostAddress()); //返回:192.168.1.100 System.out.println(addr.getHostName()); //输出计算机名 //根据域名得到InetAddress对象 addr = InetAddress.getByName("www.163.com"); System.out.println(addr.getHostAddress()); //返回 163服务器的ip:61.135.253.15 System.out.println(addr.getHostName()); //输出:www.163.com //根据ip得到InetAddress对象 addr = InetAddress.getByName("61.135.253.15"); System.out.println(addr.getHostAddress()); //返回 163服务器的ip:61.135.253.15 System.out.println(addr.getHostName()); //输出ip而不是域名。如果这个IP地 址不存在或DNS服务器不允许进行IP地址和域名的映射,getHostName方法就直接返回这个IP地址。 }
//封装端口:在InetAddress基础上+端口 public static void main(String[] args) throws UnknownHostException { InetSocketAddress address = new InetSocketAddress("127.0.0.1",9999); address = new InetSocketAddress(InetAddress.getByName("127.0.0.1"),9999); System.out.println(address.getHostName()); System.out.println(address.getPort()); InetAddress addr =address.getAddress(); System.out.println(addr.getHostAddress()); //返回:地址 System.out.println(addr.getHostName()); //输出计算机名 }
UDP
/** * 客户端 * 1、创建客户端 +端口 * 2、准备数据 * 3、打包(发送的地点 及端口) * 4、发送 * 5、释放 * 思考: 89.12 数据+类型*/ public class MyClient { public static void main(String[] args) throws IOException { //1、创建客户端 +端口 DatagramSocket client = new DatagramSocket(6666); //2、准备数据 String msg ="udp编程"; byte[] data =msg.getBytes(); //3、打包(发送的地点 及端口) DatagramPacket(byte[] buf, int length, InetAddress address, int port) DatagramPacket packet = new DatagramPacket(data,data.length,new InetSocketAddress("localhost",8888)); //4、发送 client.send(packet); //5、释放 client.close(); } }
/** * 服务端 * 1、创建服务端 +端口 * 2、准备接受容器 * 3、封装成 包 * 4、接受数据 * 5、分析数据 * 6、释放 * */ public class MyServer { public static void main(String[] args) throws IOException { //1、创建服务端 +端口 DatagramSocket server = new DatagramSocket(8888); //2、准备接受容器 byte[] container = new byte[1024]; //3、封装成 包 DatagramPacket(byte[] buf, int length) DatagramPacket packet =new DatagramPacket(container, container.length) ; //4、接受数据 server.receive(packet); //5、分析数据 byte[] data =packet.getData(); int len =packet.getLength(); System.out.println(new String(data,0,len)); //6、释放 server.close(); }
/** * 客户端 * 1、创建客户端 +端口 * 2、准备数据 double -->字节数组 字节数组输出流 * 3、打包(发送的地点 及端口) * 4、发送 * 5、释放 * * * @author Administrator * */ public class Client { public static void main(String[] args) throws IOException { //1、创建客户端 +端口 DatagramSocket client = new DatagramSocket(6666); //2、准备数据 double num =89.12; byte[] data =convert(num); //3、打包(发送的地点 及端口) DatagramPacket(byte[] buf, int length, InetAddress address, int port) DatagramPacket packet = new DatagramPacket(data,data.length,new InetSocketAddress("localhost",8888)); //4、发送 client.send(packet); //5、释放 client.close(); } /** * 字节数组 数据源 +Data 输出流*/ public static byte[] convert(double num) throws IOException{ byte[] data =null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos =new DataOutputStream(bos); dos.writeDouble(num); dos.flush(); //获取数据 data = bos.toByteArray(); dos.close(); return data; } }
/** * 服务端 * 1、创建服务端 +端口 * 2、准备接受容器 * 3、封装成 包 * 4、接受数据 * 5、分析数据 字节数组-->double * 6、释放*/ public class Server { public static void main(String[] args) throws IOException { //1、创建服务端 +端口 DatagramSocket server = new DatagramSocket(8888); //2、准备接受容器 byte[] container = new byte[1024]; //3、封装成 包 DatagramPacket(byte[] buf, int length) DatagramPacket packet =new DatagramPacket(container, container.length) ; //4、接受数据 server.receive(packet); //5、分析数据 double data =convert(packet.getData()); System.out.println(data); //6、释放 server.close(); } /** * 字节数组 +Data 输入流*/ public static double convert(byte[] data) throws IOException{ DataInputStream dis =new DataInputStream(new ByteArrayInputStream(data)); double num =dis.readDouble(); dis.close(); return num; } }
URL
package com.bjsxt.net.url;public class URLDemo01 { public static void main(String[] args) throws MalformedURLException { //绝对路径构建 URL url = new URL("http://www.baidu.com:80/index.html?uname=bjsxt"); System.out.println("协议:"+url.getProtocol()); System.out.println("域名:"+url.getHost()); System.out.println("端口:"+url.getPort()); System.out.println("资源:"+url.getFile()); System.out.println("相对路径:"+url.getPath()); System.out.println("锚点:"+url.getRef()); //锚点 System.out.println("参数:"+url.getQuery());//?参数 :存在锚点 返回null ,不存在,返回正确 url = new URL("http://www.baidu.com:80/a/"); url = new URL(url,"b.txt"); //相对路径 System.out.println(url.toString()); } }
package com.bjsxt.net.url;/** * 获取资源:源代码*/ public class URLDemo02 { public static void main(String[] args) throws IOException { URL url = new URL("http://www.baidu.com"); //主页 默认资源 //获取资源 网络流 /* InputStream is =url.openStream(); byte[] flush = new byte[1024]; int len =0; while(-1!=(len=is.read(flush))){ System.out.println(new String(flush,0,len)); } is.close(); */ BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(),"utf-8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("baidu2.html"),"utf-8")); String msg =null; while((msg=br.readLine())!=null){ //System.out.println(msg); bw.append(msg); bw.newLine(); } bw.flush(); bw.close(); br.close(); } }
TCP
/** 1、创建客户端 必须指定服务器+端口 此时就在连接 Socket(String host, int port) 2、接收数据 +发送数据 */ public class Client { public static void main(String[] args) throws UnknownHostException, IOException { //1、创建客户端 必须指定服务器+端口 此时就在连接 Socket client = new Socket("localhost",8888); //2、接收数据 /* BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream())); String echo =br.readLine(); //阻塞式方法 System.out.println(echo); */ DataInputStream dis = new DataInputStream(client.getInputStream()); String echo = dis.readUTF(); System.out.println(echo); } }
/** 必须先启动服务器 后连接 1、创建服务器 指定端口 ServerSocket(int port) 2、接收客户端连接 3、发送数据+接收数据 */ public class Server { public static void main(String[] args) throws IOException { //1、创建服务器 指定端口 ServerSocket(int port) ServerSocket server = new ServerSocket(8888); //2、接收客户端连接 阻塞式 Socket socket =server.accept(); System.out.println("一个客户端建立连接"); //3、发送数据 String msg ="欢迎使用"; //输出流 /* BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())); bw.write(msg); bw.newLine(); bw.flush(); */ DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeUTF(msg); dos.flush(); } }
/** 必须先启动服务器 后连接 1、创建服务器 指定端口 ServerSocket(int port) 2、接收客户端连接 3、发送数据+接收数据 接收多个客户端 */ public class MultiServer { public static void main(String[] args) throws IOException { //1、创建服务器 指定端口 ServerSocket(int port) ServerSocket server = new ServerSocket(8888); //2、接收客户端连接 阻塞式 while(true){ //死循环 一个accept()一个客户端 Socket socket =server.accept(); System.out.println("一个客户端建立连接"); //3、发送数据 String msg ="欢迎使用"; //输出流 DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeUTF(msg); dos.flush(); while(true){ } } } }
chat
/** * 创建客户端: 发送数据+接收数据 * 写出数据:输出流 * 读取数据:输入流 输入流 与输出流 在同一个线程内 应该 独立处理,彼此独立*/ public class Client { public static void main(String[] args) throws UnknownHostException, IOException { Socket client = new Socket("localhost",9999); //控制台输入流 BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); DataOutputStream dos = new DataOutputStream(client.getOutputStream()); DataInputStream dis = new DataInputStream(client.getInputStream()); while(true){ String info =console.readLine(); //输出流 dos.writeUTF(info); dos.flush(); //输入流 String msg =dis.readUTF(); System.out.println(msg); } } }
/** * 创建服务器 * 写出数据:输出流 * 读取数据:输入流*/ public class Server { public static void main(String[] args) throws IOException { ServerSocket server =new ServerSocket(9999); Socket client =server.accept(); //写出数据 //输入流 DataInputStream dis = new DataInputStream(client.getInputStream()); String msg =dis.readUTF(); //输出流 DataOutputStream dos = new DataOutputStream(client.getOutputStream()); dos.writeUTF("服务器-->"+msg); dos.flush(); } }
demo2
/** * 创建客户端: 发送数据+接收数据 * 写出数据:输出流 * 读取数据:输入流 * 输入流 与输出流 在同一个线程内 应该 独立处理,彼此独立*/ public class Client { public static void main(String[] args) throws UnknownHostException, IOException { Socket client = new Socket("localhost",9999); new Thread(new Send(client)).start(); //一条路径 new Thread(new Receive(client)).start(); //一条路径 } }
/** * 关闭流的方法*/ public class CloseUtil { public static void closeAll(Closeable... io){ for(Closeable temp:io){ try { if (null != temp) { temp.close(); } } catch (Exception e) { // TODO: handle exception } } } }
/** * 接收线程 */ public class Receive implements Runnable { //输入流 private DataInputStream dis ; //线程标识 private boolean isRunning = true; public Receive() { } public Receive(Socket client){ try { dis = new DataInputStream(client.getInputStream()); } catch (IOException e) { e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dis); } } /** * 接收数据 * @return */ public String receive(){ String msg =""; try { msg=dis.readUTF(); } catch (IOException e) { e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dis); } return msg; } @Override public void run() { //线程体 while(isRunning){ System.out.println(receive()); } } }
/** * 接收线程 * @author Administrator * */ public class Receive implements Runnable { //输入流 private DataInputStream dis ; //线程标识 private boolean isRunning = true; public Receive() { } public Receive(Socket client){ try { dis = new DataInputStream(client.getInputStream()); } catch (IOException e) { e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dis); } } /** * 接收数据 * @return */ public String receive(){ String msg =""; try { msg=dis.readUTF(); } catch (IOException e) { e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dis); } return msg; } @Override public void run() { //线程体 while(isRunning){ System.out.println(receive()); } } }
/** * 发送数据 线程 * @author Administrator * */ public class Send implements Runnable{ //控制台输入流 private BufferedReader console; //管道输出流 private DataOutputStream dos; //控制线程 private boolean isRunning =true; public Send() { console =new BufferedReader(new InputStreamReader(System.in)); } public Send(Socket client){ this(); try { dos =new DataOutputStream(client.getOutputStream()); } catch (IOException e) { //e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dos,console); } } //1、从控制台接收数据 private String getMsgFromConsole(){ try { return console.readLine(); } catch (IOException e) { //e.printStackTrace(); } return ""; } /** * 1、从控制台接收数据 * 2、发送数据 */ public void send(){ String msg = getMsgFromConsole(); try { if(null!=msg&& !msg.equals("")){ dos.writeUTF(msg); dos.flush(); //强制刷新 } } catch (IOException e) { //e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dos,console); } } @Override public void run() { //线程体 while(isRunning){ send(); } } }
/** * 创建服务器 * 写出数据:输出流 * 读取数据:输入流*/ public class Server { public static void main(String[] args) throws IOException { ServerSocket server =new ServerSocket(9999); while(true){ Socket client =server.accept(); //写出数据 //输入流 DataInputStream dis = new DataInputStream(client.getInputStream()); DataOutputStream dos = new DataOutputStream(client.getOutputStream()); while(true){ String msg =dis.readUTF(); System.out.println(msg); //输出流 dos.writeUTF("服务器-->"+msg); dos.flush(); } } } }
demo3
/** * 创建客户端: 发送数据+接收数据 * 写出数据:输出流 * 读取数据:输入流 * 输入流 与输出流 在同一个线程内 应该 独立处理,彼此独立*/ public class Client { public static void main(String[] args) throws UnknownHostException, IOException { Socket client = new Socket("localhost",9999); new Thread(new Send(client)).start(); //一条路径 new Thread(new Receive(client)).start(); //一条路径 } }
/** * 关闭流的方法*/ public class CloseUtil { public static void closeAll(Closeable... io){ for(Closeable temp:io){ try { if (null != temp) { temp.close(); } } catch (Exception e) { // TODO: handle exception } } } }
/** * 接收线程 */ public class Receive implements Runnable { //输入流 private DataInputStream dis ; //线程标识 private boolean isRunning = true; public Receive() { } public Receive(Socket client){ try { dis = new DataInputStream(client.getInputStream()); } catch (IOException e) { e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dis); } } /** * 接收数据 * @return */ public String receive(){ String msg =""; try { msg=dis.readUTF(); } catch (IOException e) { e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dis); } return msg; } @Override public void run() { //线程体 while(isRunning){ System.out.println(receive()); } } }
/** * 发送数据 线程*/ public class Send implements Runnable{ //控制台输入流 private BufferedReader console; //管道输出流 private DataOutputStream dos; //控制线程 private boolean isRunning =true; public Send() { console =new BufferedReader(new InputStreamReader(System.in)); } public Send(Socket client){ this(); try { dos =new DataOutputStream(client.getOutputStream()); } catch (IOException e) { //e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dos,console); } } //1、从控制台接收数据 private String getMsgFromConsole(){ try { return console.readLine(); } catch (IOException e) { //e.printStackTrace(); } return ""; } /** * 1、从控制台接收数据 * 2、发送数据 */ public void send(){ String msg = getMsgFromConsole(); try { if(null!=msg&& !msg.equals("")){ dos.writeUTF(msg); dos.flush(); //强制刷新 } } catch (IOException e) { //e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dos,console); } } @Override public void run() { //线程体 while(isRunning){ send(); } } }
/** * 创建服务器 * 写出数据:输出流 * 读取数据:输入流 * @author Administrator * */ public class Server { private List<MyChannel> all = new ArrayList<MyChannel>(); public static void main(String[] args) throws IOException { new Server().start(); } public void start() throws IOException{ ServerSocket server =new ServerSocket(9999); while(true){ Socket client =server.accept(); MyChannel channel = new MyChannel(client); all.add(channel);//统一管理 new Thread(channel).start(); //一条道路 } } /** * 一个客户端 一条道路 * 1、输入流 * 2、输出流 * 3、接收数据 * 4、发送数据*/ private class MyChannel implements Runnable{ private DataInputStream dis ; private DataOutputStream dos ; private boolean isRunning =true; public MyChannel(Socket client ) { try { dis = new DataInputStream(client.getInputStream()); dos = new DataOutputStream(client.getOutputStream()); } catch (IOException e) { //e.printStackTrace(); CloseUtil.closeAll(dis,dos); isRunning =false; } } /** * 读取数据 * @return */ private String receive(){ String msg =""; try { msg=dis.readUTF(); } catch (IOException e) { //e.printStackTrace(); CloseUtil.closeAll(dis); isRunning =false; all.remove(this); //移除自身 } return msg; } /** * 发送数据 */ private void send(String msg){ if(null==msg ||msg.equals("")){ return ; } try { dos.writeUTF(msg); dos.flush(); } catch (IOException e) { //e.printStackTrace(); CloseUtil.closeAll(dos); isRunning =false; all.remove(this); //移除自身 } } /** * 发送给其他客户端 */ private void sendOthers(){ String msg = this.receive(); //遍历容器 for(MyChannel other:all){ if(other ==this){ continue; } //发送其他客户端 other.send(msg); } } @Override public void run() { while(isRunning){ sendOthers(); } } } }
demo4
/** * 创建客户端: 发送数据+接收数据 * 写出数据:输出流 * 读取数据:输入流 输入流 与输出流 在同一个线程内 应该 独立处理,彼此独立 加入名称*/ public class Client { public static void main(String[] args) throws UnknownHostException, IOException { System.out.println("请输入名称:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String name = br.readLine(); if(name.equals("")){ return; } Socket client = new Socket("localhost",9999); new Thread(new Send(client,name)).start(); //一条路径 new Thread(new Receive(client)).start(); //一条路径 } }
/** * 关闭流的方法*/ public class CloseUtil { public static void closeAll(Closeable... io){ for(Closeable temp:io){ try { if (null != temp) { temp.close(); } } catch (Exception e) { // TODO: handle exception } } } }
/** * 接收线程 */ public class Receive implements Runnable { //输入流 private DataInputStream dis ; //线程标识 private boolean isRunning = true; public Receive() { } public Receive(Socket client){ try { dis = new DataInputStream(client.getInputStream()); } catch (IOException e) { e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dis); } } /** * 接收数据 * @return */ public String receive(){ String msg =""; try { msg=dis.readUTF(); } catch (IOException e) { e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dis); } return msg; } @Override public void run() { //线程体 while(isRunning){ System.out.println(receive()); } } }
* 发送数据 线程 public class Send implements Runnable{ //控制台输入流 private BufferedReader console; //管道输出流 private DataOutputStream dos; //控制线程 private boolean isRunning =true; //名称 private String name; public Send() { console =new BufferedReader(new InputStreamReader(System.in)); } public Send(Socket client,String name){ this(); try { dos =new DataOutputStream(client.getOutputStream()); this.name =name; send(this.name); } catch (IOException e) { //e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dos,console); } } //1、从控制台接收数据 private String getMsgFromConsole(){ try { return console.readLine(); } catch (IOException e) { //e.printStackTrace(); } return ""; } /** * 1、从控制台接收数据 * 2、发送数据 */ public void send(String msg){ try { if(null!=msg&& !msg.equals("")){ dos.writeUTF(msg); dos.flush(); //强制刷新 } } catch (IOException e) { //e.printStackTrace(); isRunning =false; CloseUtil.closeAll(dos,console); } } @Override public void run() { //线程体 while(isRunning){ send(getMsgFromConsole()); } } }
* 创建服务器 * 写出数据:输出流 * 读取数据:输入流 public class Server { private List<MyChannel> all = new ArrayList<MyChannel>(); public static void main(String[] args) throws IOException { new Server().start(); } public void start() throws IOException{ ServerSocket server =new ServerSocket(9999); while(true){ Socket client =server.accept(); MyChannel channel = new MyChannel(client); all.add(channel);//统一管理 new Thread(channel).start(); //一条道路 } } /** * 一个客户端 一条道路 * 1、输入流 * 2、输出流 * 3、接收数据 * 4、发送数据 * @author Administrator * */ private class MyChannel implements Runnable{ private DataInputStream dis ; private DataOutputStream dos ; private boolean isRunning =true; private String name; public MyChannel(Socket client ) { try { dis = new DataInputStream(client.getInputStream()); dos = new DataOutputStream(client.getOutputStream()); this.name =dis.readUTF(); this.send("欢迎您进入聊天室"); sendOthers(this.name+"进入了聊天室",true); } catch (IOException e) { //e.printStackTrace(); CloseUtil.closeAll(dis,dos); isRunning =false; } } /** * 读取数据 * @return */ private String receive(){ String msg =""; try { msg=dis.readUTF(); } catch (IOException e) { //e.printStackTrace(); CloseUtil.closeAll(dis); isRunning =false; all.remove(this); //移除自身 } return msg; } /** * 发送数据 */ private void send(String msg){ if(null==msg ||msg.equals("")){ return ; } try { dos.writeUTF(msg); dos.flush(); } catch (IOException e) { //e.printStackTrace(); CloseUtil.closeAll(dos); isRunning =false; all.remove(this); //移除自身 } } /** * 发送给其他客户端 */ private void sendOthers(String msg,boolean sys){ //是否为私聊 约定 if(msg.startsWith("@")&& msg.indexOf(":")>-1 ){ //私聊 //获取name String name =msg.substring(1,msg.indexOf(":")); String content = msg.substring(msg.indexOf(":")+1); for(MyChannel other:all){ if(other.name.equals(name)){ other.send(this.name+"对您悄悄地说:"+content); } } }else{ //遍历容器 for(MyChannel other:all){ if(other ==this){ continue; } if(sys){ //系统信息 other.send("系统信息:"+msg); }else{ //发送其他客户端 other.send(this.name+"对所有人说:"+msg); } } } } @Override public void run() { while(isRunning){ sendOthers(receive(),false); } } } }