Java 套接字Socket
生活随笔
收集整理的這篇文章主要介紹了
Java 套接字Socket
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
套接字
一、概述
二、SocketAddress類(lèi)
代碼:
import java.net.InetSocketAddress; //地址類(lèi) public class Test_01 {public static void main(String[] args) {//每次計(jì)算機(jī)介入互聯(lián)網(wǎng)時(shí)都會(huì)被自動(dòng)分配一個(gè)IP地址 , 每次都會(huì)變//127.0.0.1 永遠(yuǎn)指向本機(jī)//localhost也表示本機(jī) InetSocketAddress isa = new InetSocketAddress("www.baidu.com",5555);//獲取地址System.out.println(isa.getAddress());//獲取計(jì)算機(jī)名//如果不是本機(jī)IP , 則試圖從網(wǎng)絡(luò)獲取 , 如果獲取失敗則返回IP地址 System.out.println(isa.getHostName());//獲取端口號(hào)System.out.println(isa.getPort());} }三、UDP傳輸協(xié)議
代碼:
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;//UDP發(fā)送端/** 1. 創(chuàng)建套接字對(duì)象* 2. 數(shù)據(jù)封包* 3. 發(fā)送數(shù)據(jù)* 4. 關(guān)流* */ public class UDPSender_01 {public static void main(String[] args) throws IOException {//UDP發(fā)送端的套接字對(duì)象DatagramSocket ds = new DatagramSocket();//對(duì)數(shù)據(jù)進(jìn)行封包//第一個(gè)參數(shù):字節(jié)數(shù)組 , 數(shù)組中放的是實(shí)際數(shù)據(jù)//第二個(gè)參數(shù): 字節(jié)數(shù)組的大小 (數(shù)據(jù)的字節(jié)個(gè)數(shù))//第三個(gè)參數(shù):發(fā)送地址 DatagramPacket dp =new DatagramPacket("你好".getBytes(), "你好".getBytes().length,new InetSocketAddress("localhost" , 9999));//發(fā)送數(shù)據(jù)ds.send(dp);//關(guān)流ds.close();} } import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket;//UDP接收端 /** 1. 創(chuàng)建套接字對(duì)象* 2. 準(zhǔn)備數(shù)據(jù)報(bào)* 3. 接收數(shù)據(jù)* 4. 讀取數(shù)據(jù)* */ public class UDPReciever_01 {public static void main(String[] args) throws IOException {//創(chuàng)建套接字對(duì)象 , 并指定端口 DatagramSocket ds = new DatagramSocket(9999);//準(zhǔn)備一個(gè)數(shù)據(jù)報(bào)//第一個(gè)參數(shù): 一個(gè)字節(jié)數(shù)組 , 表示作為存儲(chǔ)接收數(shù)據(jù)的容器//第二個(gè)參數(shù): 表示指定容器的大小DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);//接收數(shù)據(jù)//在沒(méi)有接收到數(shù)據(jù)時(shí)處于阻塞狀態(tài) ds.receive(dp);//關(guān)流ds.close();//將數(shù)據(jù)從數(shù)據(jù)包中解析出來(lái)byte[] bs = dp.getData();//獲取數(shù)據(jù)存儲(chǔ)數(shù)據(jù)的直接數(shù)組 int len = dp.getLength();//獲取實(shí)際數(shù)據(jù)長(zhǎng)度System.out.println(new String(bs ,0, len));//可以獲取發(fā)送地址System.out.println(dp.getAddress());//獲取發(fā)送用的端口號(hào) 端口號(hào)會(huì)一直變 , 這是為什么?System.out.println(dp.getPort());} }練習(xí):單人聊天室
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.util.Scanner;//單人聊天 發(fā)送端 public class UDPIMSender_03 implements Runnable {@Overridepublic void run() {// 創(chuàng)建套接字try {DatagramSocket ds = new DatagramSocket();// 創(chuàng)建數(shù)據(jù)報(bào)Scanner in = new Scanner(System.in);//獲取數(shù)據(jù)while(true){System.out.println("回車(chē)發(fā)送:");String str = in.nextLine();DatagramPacket dp = new DatagramPacket(str.getBytes(),str.getBytes().length, new InetSocketAddress("localhost",10000));// 發(fā)送數(shù)據(jù)ds.send(dp);if(str.equals("over")){System.out.println("發(fā)送端結(jié)束");break;}}//關(guān)流ds.close();} catch (IOException e) {// TODO 自動(dòng)生成的 catch 塊e.printStackTrace();}} } import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException;//UDP聊天室 接收端 public class UDPIMReciever_03 implements Runnable{@Overridepublic void run() {//創(chuàng)建套接字對(duì)象try {DatagramSocket ds = new DatagramSocket(10000);//創(chuàng)建數(shù)據(jù)包DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);//接收數(shù)據(jù)while(true){ds.receive(dp);//讀取數(shù)據(jù)byte[] data = dp.getData();String str = new String(data , 0 , data.length);if("over".equals(str.trim())){System.out.println("接收端結(jié)束");break;}System.out.println("客戶(hù)端發(fā)來(lái):"+str);}//關(guān)流ds.close();} catch (IOException e) {e.printStackTrace();}}} //單人聊天 public class Test_03 {public static void main(String[] args) {//開(kāi)啟聊天new Thread(new UDPIMReciever_03()).start();new Thread(new UDPIMSender_03()).start();} }四、TCP傳輸協(xié)議
代碼:
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket;public class TCPServer_01 {public static void main(String[] args) throws IOException {//創(chuàng)建套接字 , 并綁定端口號(hào)ServerSocket ss = new ServerSocket(7000);//接受連接//阻塞Socket s = ss.accept();//讀取數(shù)據(jù)InputStream is = s.getInputStream();byte[] bs = new byte[1024];int len = -1;while((len = is.read(bs))!=-1){System.out.println(new String(bs));}//向客戶(hù)端響應(yīng)信息OutputStream out = s.getOutputStream();out.write("接受成功!".getBytes());//關(guān)流ss.close();s.shutdownOutput();} } import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket;public class TCPCilent_01 {public static void main(String[] args) throws IOException {//創(chuàng)建客戶(hù)端套接字對(duì)象Socket s = new Socket();//客戶(hù)端發(fā)起連接 , 綁定鏈接地址//連接時(shí)會(huì)發(fā)生阻塞s.connect(new InetSocketAddress("localhost", 7000));//獲取一個(gè)輸出流OutputStream out = s.getOutputStream();//寫(xiě)出數(shù)據(jù)out.write("你好".getBytes());//通知服務(wù)器端 數(shù)據(jù)已經(jīng)寫(xiě)出完畢s.shutdownOutput();//接服務(wù)器端響應(yīng)InputStream in = s.getInputStream();byte[] bs = new byte[1024];int len = -1;while((len = in.read(bs)) != -1){System.out.println(new String(bs));}//關(guān)流s.close();} }練習(xí): 上傳文件 — 文件名不能變
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket;public class TCPServer_04 {public static void main(String[] args) throws IOException {//創(chuàng)建套接字對(duì)象 , 并指定端口ServerSocket ss = new ServerSocket(7777);//接受連接Socket s = ss.accept();//獲取輸入流InputStream is = s.getInputStream();//讀取文件名字節(jié)個(gè)數(shù)int count= is.read();//讀取文件名byte[] name = new byte[count];is.read(name);//創(chuàng)建文件實(shí)例File file = new File("C:\\Users\\user\\Desktop\\暫存\\副本 -- "+new String(name));FileOutputStream fos = new FileOutputStream(file);//讀取數(shù)據(jù)int len = -1 ; byte bs[] = new byte[1024];while((len = is.read(bs)) != -1){System.out.println(new String(bs , 0, len));fos.write(bs, 0, len);}s.shutdownInput();fos.close();System.out.println("接收成功");//向客戶(hù)端響應(yīng)信息OutputStream out = s.getOutputStream();out.write("接收完成!".getBytes());//關(guān)流s.shutdownOutput();} } import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; //上傳文件客戶(hù)端public class TCPClient_04 {public static void main(String[] args) throws IOException {//創(chuàng)建文件實(shí)例File file = new File("C:\\Users\\user\\Desktop\\暫存\\c.txt");//獲取文件名字String name = file.getName();//創(chuàng)建套接字Socket s= new Socket();//建立連接s.connect(new InetSocketAddress("localhost" , 7777));//獲取輸出流OutputStream out = s.getOutputStream();//輸出文件名字節(jié)個(gè)數(shù)out.write(name.length());//輸出文件名out.write(name.getBytes());//讀取文件并寫(xiě)出FileInputStream fis = new FileInputStream(file);BufferedReader br = new BufferedReader(new InputStreamReader(fis));String line = null;while((line = br.readLine()) != null){out.write(line.getBytes());}//通知服務(wù)端寫(xiě)出完畢s.shutdownOutput();//向客戶(hù)端響應(yīng)信息InputStream in = s.getInputStream();byte[] inbs = new byte[1024];in.read(inbs);if(new String(inbs).trim().equals("接收完成!")){System.out.println("發(fā)送成功");}else{System.out.println("發(fā)送失敗");}//關(guān)流s.shutdownInput();} }五、擴(kuò)展
總結(jié)
以上是生活随笔為你收集整理的Java 套接字Socket的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java 设计模式 --- 单例模式
- 下一篇: Java中的八种锁