InerAddress:
/**IP地址:在網絡上唯一標示一台計算機
* 端口號:標示計算機上不同的應用程序
* java.net.InetAddress類:此類表示互聯網協議 (IP) 地址。
* 常用方法:
* getByName(String host) 在給定主機名的情況下確定主機的 IP 地址。
* getHostName() 獲取此 IP地址的主機名。
* getHostAddress()返回 IP 地址字符串(以文本表現形式)。
* getLocalHost() 返回本地主機。
* getAllByName(String host) 在給定主機名的情況下,根據系統上配置的名稱服務返回其 IP 地址所組成的數組。
*
*/
public class TestInetAddress { public static void main(String[] args) { try { //在給定主機名的情況下確定主機的 IP 地址。 // InetAddress inetAddress = InetAddress.getByName("P-PC"); InetAddress inetAddress = InetAddress.getLocalHost();//獲取本地主機 System.out.println(inetAddress); String hostName = inetAddress.getHostName(); System.out.println("主機名:"+hostName); String ip = inetAddress.getHostAddress(); System.out.println("IP地址:"+ip); //根據主機名或域名獲取其IP地址 InetAddress[] ids = InetAddress.getAllByName("www.baidu.com"); for (InetAddress inetAddress2 : ids) { System.out.println(inetAddress2); } } catch (UnknownHostException e) { e.printStackTrace(); } } }
InetSocketAddress:
*java.net.InetSocketAddress類:此類實現 IP 套接字地址(IP 地址 + 端口號)。
*構造方法
*InetSocketAddress(InetAddress addr, int port)根據 IP 地址和端口號創建套接字地址。
*InetSocketAddress(String hostname, int port) 根據主機名和端口號創建套接字地址。
*常用的方法:
* getAddress():獲取 InetAddress。
* getPort() 獲取端口號。
* toString() 構造此 InetSocketAddress 的字符串表示形式。(主機名/Ip:端口號)
* getHostName()獲取 主機名。
public class TestInetSocketAddress { public static void main(String[] args) { // InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",3306); try { InetSocketAddress socketAddress = new InetSocketAddress(InetAddress.getLocalHost(), 3306); System.out.println(socketAddress); InetAddress inetAddress = socketAddress.getAddress(); System.out.println("主機信息:"+inetAddress); int port = socketAddress.getPort(); System.out.println("端口號:"+port); String hostName = socketAddress.getHostName(); System.out.println("主機名:"+hostName); } catch (UnknownHostException e) { e.printStackTrace(); } } }
URL:
*URL:統一資源定位符
*組成部分:協議,主機名或IP,端口號,資源路徑
*java.net.URL類:代表一個統一資源定位符,它是指向互聯網“資源”的指針
* 常用的構造方法
* URL(String spec) 根據 String 表示形式創建 URL 對象。
* URL(String protocol, String host, int port, String file) 根據指定 protocol、host、port 號和 file 創建 URL 對象。
* 常用的方法:
* getProtocol()獲取此 URL 的協議名稱。
* getHost()獲取此 URL 的主機名(如果適用)。
* getPort() 獲取此 URL 的端口號。
* getFile()獲取此 URL 的文件名。
* getDefaultPort()獲取與此 URL 關聯協議的默認端口號。
* getPath()獲取此 URL 的路徑部分。
* ...
public class TestURL { public static void main(String[] args) { try { URL url = new URL("http://www.baidu.com/index.html#aa?cansu=bjsxt"); String protocol = url.getProtocol(); System.out.println("協議:"+protocol); String host = url.getHost(); System.out.println("主機名:"+host); int port = url.getPort(); System.out.println("端口號:"+port); int defualtPort = url.getDefaultPort(); System.out.println("默認端口:"+defualtPort); String file = url.getFile(); System.out.println("資源路徑:"+file); String path = url.getPath(); System.out.println("資源路徑:"+path); } catch (MalformedURLException e) { e.printStackTrace(); } } }
URL類
* InputStream openStream() 打開到此 URL 的連接並返回一個用於從該連接讀入的 InputStream。
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; public class WebSpider { public static void main(String[] args) { try { URL url = new URL("https://channel.jd.com/men.html"); InputStream ips = url.openStream(); InputStreamReader isr = new InputStreamReader(ips);//將字節流轉換為字符流 BufferedReader br = new BufferedReader(isr); String str; while((str=br.readLine())!=null){ System.out.println(str); } br.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Socket與SeverSocket信息的傳遞:
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; /** * java.net.ServerSocket類:此類實現服務器套接字。服務器套接字等待請求通過網絡傳入 * 構造方法: * ServerSocket(int port)創建綁定到特定端口的服務器套接字。 * * 常用方法: * accept() 偵聽並接受到此套接字的連接。 * close() 關閉此套接字。 * * 服務器端 */ public class SimpleServer { public static void main(String[] args) { try { System.out.println("------服務器端啟動------"); //1.創建服務器端的套接字並指定端口 ServerSocket serverSocket = new ServerSocket(8888); //2.偵聽並接受到此套接字的連接。 Socket socket = serverSocket.accept(); //3.從套接字中獲取一個輸入流 InputStream ips = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(ips); char[] cs = new char[1024]; int len = isr.read(cs); String message = new String(cs, 0, len); System.out.println("客戶端消息:"+message); isr.close(); socket.close(); serverSocket.close(); System.out.println("服務器數據接收完畢!"); } catch (IOException e) { e.printStackTrace(); } } }
import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; /** *java.net.Socket類:此類實現客戶端套接字(也可以就叫“套接字”)。套接字是兩台機器間通信的端點。 *構造方法: *Socket(InetAddress address, int port)創建一個流套接字並將其連接到指定 IP 地址的指定端口號。 *Socket(String host, int port) 創建一個流套接字並將其連接到指定主機上的指定端口號。 *常用方法: *getOutputStream()返回此套接字的輸出流。 *getInputStream() 返回此套接字的輸入流。 *close()關閉此套接字。 *客戶端 */ public class SimpleClient { public static void main(String[] args) { try { System.out.println("-------客戶端啟動-------"); //1.創建一個套接字並將其連接到指定的IP地址的指定端口 Socket socket = new Socket("127.0.0.1",8888); //2.獲取套接字的輸出流,用於輸出數據 OutputStream ops = socket.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(ops); osw.write("你好!"); osw.flush(); osw.close(); socket.close(); System.out.println("客戶端數據發送完畢!"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
根據用戶輸入的賬號密碼,從服務器上判斷是否正確並傳遞信息回來:
import java.io.Serializable; /** * 如果要對該對象進行序列化,就必須實現Serializable接口 * 封裝用戶名和密碼信息 */ public class User implements Serializable{ private String userName; private String password; public User(){ } public User(String userName,String password){ this.userName=userName; this.password=password; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
import java.io.DataInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; /** * 客戶端: * 1.獲取用戶名和密碼 * 2.將用戶名和密碼封裝成User對象 * 3.使用對象流將user對象發生到服務器端 * 4.讀取服務器的響應消息 * 5.釋放資源 */ public class LoginClient { public static void main(String[] args) { Scanner input = new Scanner(System.in); //獲取輸入的用戶名和密碼 System.out.println("請輸入用戶名:"); String userName = input.next(); System.out.println("請輸入密碼:"); String password = input.next(); //將用戶名和密碼封裝成User對象 User user = new User(userName,password); try { //創建Socket對象 Socket socket = new Socket("127.0.0.1",6666); //獲取輸出流 OutputStream ops = socket.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(ops); //使用對象流將user對象發送到服務器端 oos.writeObject(user); oos.flush(); //獲取服務器端響應消息 InputStream ips = socket.getInputStream(); DataInputStream dis = new DataInputStream(ips); String str = dis.readUTF(); System.out.println(str); //釋放資源 dis.close(); oos.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /** * 服務器端: * 1.獲取客戶端發送的user對象(封裝了用戶名和密碼) * 2.判斷用戶名和密碼是否合法 * 3.如果合法,向客戶端發送"恭喜你,登陸成功!";否則向客戶端發送"用戶名或密碼有誤!" * 4.釋放資源 */ public class LoginServer { public static void main(String[] args) { try { //1.獲取客戶端發送的用戶名和密碼信息 ServerSocket serverSocket = new ServerSocket(6666); Socket socket = serverSocket.accept(); InputStream ips = socket.getInputStream(); ObjectInputStream ois = new ObjectInputStream(ips); User user = (User)ois.readObject(); //2.判斷用戶名和密碼是否正確 String message; if("zzsxt".equals(user.getUserName())&&"zzsxt".equals(user.getPassword())){ message="恭喜你,登陸成功!"; }else{ message="用戶名或密碼有誤!"; } //3.創建輸出流向客戶端發送消息 OutputStream ops = socket.getOutputStream(); DataOutputStream dos = new DataOutputStream(ops); dos.writeUTF(message); dos.flush(); //4.釋放資源 ois.close(); dos.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
方法2:
/** * 服務器端: * 1.獲取客戶端發送的user對象(封裝了用戶名和密碼) * 2.判斷用戶名和密碼是否合法 * 3.如果合法,向客戶端發送"恭喜你,登陸成功!";否則向客戶端發送"用戶名或密碼有誤!" * 4.釋放資源 */ public class LoginServer { //用於保存用戶名和密碼的信息,利用用戶名做鍵,利用密碼做值 static Map<String,String> map = new HashMap<String,String>(); //初始化map static{ map.put("zzsxt", "zzsxt"); map.put("bjsxt", "bjsxt"); map.put("whsxt", "whsxt"); } static int count=0;//第幾位訪客 public static void main(String[] args) { //1.獲取客戶端發送的用戶名和密碼信息 ServerSocket serverSocket=null; Socket socket=null; ObjectInputStream ois =null; DataOutputStream dos=null; try { serverSocket = new ServerSocket(6666); while(true){ socket = serverSocket.accept(); InputStream ips = socket.getInputStream(); ois = new ObjectInputStream(ips); User user = (User)ois.readObject(); //2.判斷用戶名和密碼是否正確 String userName = user.getUserName();//獲取用戶輸入的用戶名 aa String password = user.getPassword();//獲取用戶輸入的密碼 String upass=map.get(userName); String message; if(upass!=null&&upass.equals(password)){ count++;//計數 message="恭喜你,登陸成功!您是第"+count+"位訪客"; }else{ message="用戶名或密碼有誤!"; } //3.創建輸出流向客戶端發送消息 OutputStream ops = socket.getOutputStream(); dos = new DataOutputStream(ops); dos.writeUTF(message); dos.flush(); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }finally{ try { //4.釋放資源 ois.close(); dos.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
方法3:轉換為多線程交互
import java.io.Serializable; /** * 如果要對該對象進行序列化,就必須實現Serializable接口 * 封裝用戶名和密碼信息 */ public class User implements Serializable{ private String userName; private String password; public User(){ } public User(String userName,String password){ this.userName=userName; this.password=password; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User [userName=" + userName + ", password=" + password + "]"; } }
public class LoginClient { public static void main(String[] args) { Scanner input = new Scanner(System.in); //獲取輸入的用戶名和密碼 System.out.println("請輸入用戶名:"); String userName = input.next(); System.out.println("請輸入密碼:"); String password = input.next(); //將用戶名和密碼封裝成User對象 User user = new User(userName,password); try { //創建Socket對象 Socket socket = new Socket("127.0.0.1",6666); //獲取輸出流 OutputStream ops = socket.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(ops); //使用對象流將user對象發送到服務器端 oos.writeObject(user); oos.flush(); //獲取服務器端響應消息 InputStream ips = socket.getInputStream(); DataInputStream dis = new DataInputStream(ips); String str = dis.readUTF(); System.out.println(str); //釋放資源 dis.close(); oos.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.OutputStream; import java.net.Socket; import java.util.HashMap; import java.util.Map; /** * 用於處理客戶端請求的線程 * @author Administrator * */ public class ServerThread extends Thread{ private Socket socket; //用於保存用戶名和密碼的信息,利用用戶名做鍵,利用密碼做值 static Map<String,String> map = new HashMap<String,String>(); //初始化map static{ map.put("zzsxt", "zzsxt"); map.put("bjsxt", "bjsxt"); map.put("whsxt", "whsxt"); } static int count=0;//第幾位訪客 //構造方法 public ServerThread(Socket socket){ this.socket=socket; } /** * 處理客戶端請求 */ @Override public void run() { ObjectInputStream ois =null; DataOutputStream dos=null; try { InputStream ips = socket.getInputStream(); ois = new ObjectInputStream(ips); User user = (User)ois.readObject(); //2.判斷用戶名和密碼是否正確 String userName = user.getUserName();//獲取用戶輸入的用戶名 aa String password = user.getPassword();//獲取用戶輸入的密碼 String upass=map.get(userName); String message; if(upass!=null&&upass.equals(password)){ count++;//計數 message="恭喜你,登陸成功!您是第"+count+"位訪客"; }else{ message="用戶名或密碼有誤!"; } //3.創建輸出流向客戶端發送消息 OutputStream ops = socket.getOutputStream(); dos = new DataOutputStream(ops); dos.writeUTF(message); dos.flush(); } catch (IOException |ClassNotFoundException e) { e.printStackTrace(); }finally{ try { ois.close(); dos.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
/** * 面臨的問題: * 當多個用戶同時登陸時,只能排隊等待。 * 解決方案:使用多線程進行解決,為每一個客戶請求創建線程,為其提供服務。 * * 服務器端: * 1.獲取客戶端發送的user對象(封裝了用戶名和密碼) * 2.判斷用戶名和密碼是否合法 * 3.如果合法,向客戶端發送"恭喜你,登陸成功!";否則向客戶端發送"用戶名或密碼有誤!" * 4.釋放資源 * */ public class LoginServer { public static void main(String[] args) { //1.獲取客戶端發送的用戶名和密碼信息 ServerSocket serverSocket=null; try { serverSocket = new ServerSocket(6666); while(true){ Socket socket = serverSocket.accept(); //啟動線程,處理用戶請求 new ServerThread(socket).start(); } } catch (IOException e) { e.printStackTrace(); }finally{ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
TCP與UDP的區別:
1.TCP與UDP基本區別
1.基於連接與無連接,TCP是面向連接,UDP是不面向連接;
2.TCP要求系統資源較多效率低,UDP較占用資源少;
3.UDP程序結構較簡單,TCP點到點的通信,UDP可以廣播發送 ;
4.流模式(TCP)與數據報模式(UDP);
5.TCP保證數據正確性,UDP可能丟包(發送不管對方是否准備好,接收方收到也無確認);
6.TCP保證數據順序,UDP不保證 ;
2.UDP應用場景:
1.面向數據報方式
2.網絡數據大多為短消息
3.擁有大量Client
4.對數據安全性無特殊要求
5.網絡負擔非常重,但對響應速度要求高
3.具體編程時的區別
1.socket()的參數不同
2.UDP Server不需要調用listen和accept
3.UDP收發數據用sendto/recvfrom函數
4.TCP:地址信息在connect/accept時確定
5.UDP:在sendto/recvfrom函數中每次均 需指定地址信息
6.UDP:shutdown函數無效