網絡編程(Socket編程基礎)

計算機網絡

  • 計算機網絡定義:
    • 計算機網絡是指將地理位置不同的具有獨立功能的多臺計算機及其外部設備,通過通信線路連接起來,在網絡操作系統,網絡管理軟件及網絡通信協議的管理和協調下,實現資源共享和信息傳遞的計算機系統。

網絡通信協議

  • 網絡通信協議
    • 計算機網絡中實現通信必須有一些約定即通信協議,對速率、傳輸代碼、代碼結構、傳輸控制步驟、出錯控制等制定標準。好比公路交通規則,學生守則。
  • ISO/OSI參考模型
    分爲7層(從底到高):
    物理層---->數據鏈路層---->網絡層---->傳輸層---->會話層---->表示層---->應用層
  • TCP/IP協議棧:
    分爲4層(同上):
    物理+數據鏈路層---->網絡層(IP)---->傳輸層(TCP/UDP)---->應用層
  • 1、封裝(發送數據)
  • 2、拆裝(接收數據)
    TCP協議和UDP協議
  • Socket套接字
    Socket實際是網絡傳輸層供給應用層的編程接口。傳輸層則在網絡層的基礎上提供進程到進程問的邏輯通道,而應用層的進程則利用傳輸層向另一臺主機的某一進程通信。Socket就是應用層與傳輸層之間的橋樑
    使用Socket編程可以開發客戶機和服務器應用程序,可以在本地網絡上進行通信,也可通過Internet在全球範圍內通信
  • TCP編程
    用戶輸入用戶名密碼,服務器給出登錄成功或失敗的提示;使用基於TCP協議的Socket網絡編程實現;在網絡通訊中,第一次主動發起通訊的程序被稱作客戶端(Client)程序,第一次通訊中等待連接的程序被稱作服務器端(Server)程序,利用IO流實現數據的傳輸。
  • 客戶端發送信息:
public class ClientSocket1 {
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("客戶端");
Socket socket = new Socket("接收端的IP",20000);
OutputStream  os=socket.getOutputStream();
DataOutputStream dos= new DataOutputStream(os);
		dos.writeUTF("Hello");
		dos.flush();
		dos.close();
	}
}
  • 服務器接收信息:
public class ServerSocket2 {
public static void main(String[] args) throws IOException {
	System.out.println("服務器");
ServerSocket serverSocket = new ServerSocket();
Socket client=serverSocket.accept();
InputStream is=client.getInputStream();
DataInputStream dis = new DataInputStream(is);
		dis.readUTF();
		dis.close();
		is.close();
		client.close();
	}
}

在這裏面我把異常全部拋出去了,你們練習的時候自己解決

  • 實現倆個人在控制檯聊天:
    客戶端:
public class Socket1 {
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("客戶端啓動");
Scanner scanner = new Scanner(System.in);
while(true){
Socket socket = new Socket("接收端的IP", 15980);//後面端口號
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(scanner.next());
ServerSocket serverSocket = new ServerSocket(15980);//端口號
Socket socket1 = serverSocket.accept();
DataInputStream dis = new DataInputStream(socket1.getInputStream());
			dis.readUTF();
			dis.close();
			dos.close();
		}
	}
}

服務端:

public class ServerSocket1 {
public static void main(String[] args) throws IOException {
System.out.println("服務器啓動");
Scanner scanner = new Scanner(System.in);
while (true) {
ServerSocket serverSocket = new ServerSocket(15980);
Socket socket1 = serverSocket.accept();
DataInputStream dis = new DataInputStream(socket1.getInputStream());
System.out.println(socket1.getInetAddress() + "發送:" + dis.readUTF());
Socket socket = new Socket("192.168.88.212", 15980);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
			dos.writeUTF(scanner.next());
			dis.close();
			dos.close();
		}
	}
}
  • UDP編程
  • 用UDP實現倆人在控制檯聊天,輸入bye結束
    客戶端:
public class AskClient {
public static void main(String[] args) throws IOException {
	System.out.println("客戶端啓動");
DatagramSocket ds = new DatagramSocket();// 端口接收數據
Scanner scanner = new Scanner(System.in);
	while (true) {
		String str = scanner.nextLine();
		byte[] buf1 = new byte[1024];
		DatagramPacket dp1 = new DatagramPacket(buf1, buf1.length, InetAddress.getByName("192.168.88.123"), 20005);
		ds.receive(dp1);
		byte[] buf = str.getBytes();
		DatagramPacket dp = new DatagramPacket(buf, buf.length);
		ds.send(dp);
		System.out.println("收到的數據:" + new String(dp1.getData()));
		if ("bye".equals(str)) {
				break;
			}
		}
		ds.close();
	}
}

服務器端:

public class AskServer {
public static void main(String[] args) throws IOException {
System.out.println("在線客服  服務器正在啓動-----");
Scanner scanner = new Scanner(System.in);
DatagramSocket ds = new DatagramSocket(20005);
	while (true) {
		byte[] buf = new byte[1024];
		DatagramPacket dp = new DatagramPacket(buf, buf.length);
		ds.receive(dp);
		String info = new String(dp.getData());
		System.out.println("收到數據" + info);
		String str = scanner.nextLine();
		byte[] buf1 = str.getBytes();
		DatagramPacket dp1 = new DatagramPacket(buf1, buf1.length, dp.getAddress(), dp.getPort());
			ds.send(dp1);
			if ("bye".equals(info)) {
				break;
			}
		}
		ds.close();
	}
}

URl

URL u = new URL("https://www.baidu.com/");
System.out.println("獲取與此url關聯的協議的默認端口:"+u.getDefaultPort());
System.out.println(“getFile:”+u.getFile());  //端口號後面的內容
System.out.println("主機名:"+u.getHost());  //www.google.cn
System.out.println(“路徑:”+u.getPath());  //端口號後,參數前的內容
System.out.println(“端口:”+u.getPort());  //存在返回80.否則返回-1
System.out.println("協議:"+u.getProtocol()); 
System.out.println("參數部分:"+u.getQuery()); 
System.out.println("錨點:"+u.getRef()); 


把網絡上的圖片寫到本地:

public class DownImageUtils {
	String usrStr;
	File file;
	public void downImagefile(String arr, File file2) {
		HttpURLConnection hu = null;
		FileOutputStream fos = null;
		URL url = null;
		BufferedInputStream bis = null;
		try {
			url = new URL(usrStr);
			hu = (HttpURLConnection) url.openConnection();
			hu.connect();
			bis = new BufferedInputStream(hu.getInputStream());
			fos = new FileOutputStream(file);
			byte[] buf = new byte[512];
			int len = -1;
			while ((len = bis.read(buf)) != -1) {
				fos.write(buf, 0, len);
				fos.flush();
			}
		} catch (MalformedURLException e) {
			System.out.println("URL連接");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("");
			e.printStackTrace();
		} finally {
			try {
				fos.close();
				bis.close();
				hu.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
public static void main(String[] args) {
		String[] arr = {
				"http://img.sccnn.com/bimg/339/17195.jpg",
				"http://img.sccnn.com/bimg/339/18041.jpg" };
		DownImage down = new DownImage();
		for (int i = 0; i <arr.length; i++) {
			down.downTmagefile(arr[i], new File("F:\\"+i+"a.jpg"));
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章