Java Network 01 - Socket and IO

該文只涉及Socket和IO(不含NIO)


網(wǎng)絡(luò)跟我們息息相關(guān)

復(fù)習(xí)經(jīng)典網(wǎng)絡(luò)結(jié)構(gòu)

OSI七層模型
數(shù)據(jù)封裝過(guò)程
實(shí)際上使用的TCP/IP模型
網(wǎng)絡(luò)協(xié)議

Socket

端點(diǎn)通信

Berkeley sockets is a Unix application programming interface (API) for Internet sockets and Unix domain sockets, used for inter-process communication (IPC). It is commonly implemented as a libraryof linkable modules. It originated with the 4.2BSD Unix released in 1983.
A socket is an abstract representation (handle) for the local endpoint of a network communication path. The Berkeley sockets API represents it as a file descriptor (file handle) in the Unix philosophy that provides a common interface for input and output to streams of data.
<<from wikipedia>>


socket通信

為了易懂,程序直接拷貝過(guò)來(lái)跃须,沒(méi)有使用接口繼承等方式站叼。

服務(wù)端程序1

package com.loyotech.bigscreenbackend.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @program big-screen-backend
 * @description 網(wǎng)絡(luò)互聯(lián), 發(fā)送消息
 * @author Rudolph Browne
 * @create 19-1-12
 */
public class ServerSocket1 {
    public static void main(String[] args) throws IOException {

        // 暴露服務(wù), 端點(diǎn)地址: 本機(jī)IP和8888
        try(ServerSocket server = new ServerSocket(8888);
            Socket socket = server.accept()) {

            System.out.println("與客戶端連接成功...");
            acceptMessage(socket);
            sendMessage(socket, "Connection Success", "服務(wù)端消息");
        }
    }

    /**
     * 發(fā)送1M的消息
     * @param socket
     * @param message
     * @throws IOException
     */
    private static void sendMessage(Socket socket, String message, String messageType) throws IOException {
        OutputStream messageOut = socket.getOutputStream();
        messageOut.write((messageType + " : " + message).getBytes());
        socket.shutdownOutput();
    }

    /**
     * 讀取1M數(shù)據(jù)量的消息
     * @param socket
     * @throws IOException
     */
    private static void acceptMessage(Socket socket) throws IOException {
        InputStream messageIn = socket.getInputStream();
        byte[] buf = new byte[1024];
        int len = messageIn.read(buf);
        System.out.println(new String(buf, 0, len));
        socket.shutdownInput();
    }
}

客戶端程序1

package com.loyotech.bigscreenbackend.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/*
 * @program big-screen-backend
 * @description
 * @author Rudolph Browne
 * @create 19-1-12
 */
public class ClientSocket1 {
    public static void main(String[] args) throws IOException {

        try(Socket socket = new Socket("192.168.0.104", 8888)) {

            sendMessage(socket, "Test Connection", "客戶端消息");
            acceptMessage(socket);
        }
    }

    /**
     * 發(fā)送1M的消息
     * @param socket
     * @param message
     * @throws IOException
     */
    private static void sendMessage(Socket socket, String message, String messageType) throws IOException {
        OutputStream messageOut = socket.getOutputStream();
        messageOut.write((messageType + " : " + message).getBytes());
        socket.shutdownOutput();
    }

    /**
     * 讀取1M數(shù)據(jù)量的消息
     * @param socket
     * @throws IOException
     */
    private static void acceptMessage(Socket socket) throws IOException {
        InputStream messageIn = socket.getInputStream();
        byte[] buf = new byte[1024];
        int len = messageIn.read(buf);
        System.out.println(new String(buf, 0, len));
        socket.shutdownInput();
    }
}

數(shù)據(jù)傳輸

傳統(tǒng)數(shù)據(jù)傳輸通道
相同的抽象-文件

服務(wù)端程序2

package com.loyotech.bigscreenbackend.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @program big-screen-backend
 * @description 網(wǎng)絡(luò)互聯(lián), 發(fā)送消息
 * @author Rudolph Browne
 * @create 19-1-12
 */
public class ServerSocket2 {
    public static void main(String[] args) throws IOException {

        // 暴露服務(wù), 端點(diǎn)地址: 本機(jī)IP和8888
        try(ServerSocket server = new ServerSocket(8888);
            Socket socket = server.accept()) {

            System.out.println("與客戶端連接成功...");
            sendFile(socket, new File("/home/harry/Desktop/Spring揭秘.pdf"));
        }
    }

    /**
     * 發(fā)送1M的消息
     * @param socket
     * @param fileDescriptor
     * @throws IOException
     */
    private static void sendFile(Socket socket, File fileDescriptor) throws IOException {

        try(FileInputStream fileInputStream = new FileInputStream(fileDescriptor)) {

            OutputStream packageOut = socket.getOutputStream();

            byte[] buf = new byte[1024]; // 1M大小的緩沖區(qū)
            int len = -1; // 每次讀文件流大小

            while((len = fileInputStream.read(buf)) != -1) {
                packageOut.write(buf, 0, len);
            }

            System.out.println("成功將文件"+ fileDescriptor.getAbsolutePath()
                    + "發(fā)送至" + socket.getInetAddress().getHostAddress());

            socket.shutdownOutput();
        }

    }

    /**
     * 讀取1M數(shù)據(jù)量的消息
     * @param socket
     * @throws IOException
     */
    private static void acceptFile(Socket socket, File fileDescriptor) throws IOException {
        try(FileOutputStream fileOutputStream = new FileOutputStream(fileDescriptor)) {
            InputStream pacakageIn = socket.getInputStream();
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = pacakageIn.read(buf)) != -1){
                fileOutputStream.write(buf, 0, len);
            }
            socket.shutdownInput();
        }
        System.out.println("從 " + socket.getInetAddress().getHostAddress() + " 接收數(shù)據(jù)," +
                "數(shù)據(jù)寫入成功,存儲(chǔ)位置: " + fileDescriptor.getAbsolutePath());
    }
}

客戶端程序2

package com.loyotech.bigscreenbackend.socket;

import java.io.*;
import java.net.Socket;

/*
 * @program big-screen-backend
 * @description
 * @author Rudolph Browne
 * @create 19-1-12
 */
public class ClientSocket2 {
    public static void main(String[] args) throws IOException {

        try(Socket socket = new Socket("192.168.0.104", 8888)) {

            acceptFile(socket, new File("/media/harry/OS/Users/Rudolph Browne/WorkingSpace/揭秘.pdf"));
        }
    }

    /**
     * 發(fā)送1M的消息
     * @param socket
     * @param fileDescriptor
     * @throws IOException
     */
    private static void sendFile(Socket socket, File fileDescriptor) throws IOException {

        try(FileInputStream fileInputStream = new FileInputStream(fileDescriptor)) {

            OutputStream packageOut = socket.getOutputStream();

            byte[] buf = new byte[1024]; // 1M大小的緩沖區(qū)
            int len = -1; // 每次讀文件流大小

            while((len = fileInputStream.read(buf)) != -1) {
                packageOut.write(buf, 0, len);
            }

            System.out.println("成功將文件"+ fileDescriptor.getAbsolutePath()
                    + "發(fā)送至" + socket.getInetAddress().getHostAddress());

            socket.shutdownOutput();
        }

    }

    /**
     * 讀取1M數(shù)據(jù)量的消息
     * @param socket
     * @throws IOException
     */
    private static void acceptFile(Socket socket, File fileDescriptor) throws IOException {
        try(FileOutputStream fileOutputStream = new FileOutputStream(fileDescriptor)) {
            InputStream pacakageIn = socket.getInputStream();
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = pacakageIn.read(buf)) != -1){
                fileOutputStream.write(buf, 0, len);
            }
            socket.shutdownInput();
        }
        System.out.println("從" + socket.getInetAddress().getHostAddress() + "接收數(shù)據(jù)," +
                "數(shù)據(jù)寫入成功,存儲(chǔ)位置: " + fileDescriptor.getAbsolutePath());
    }
}

支持多用戶并發(fā)上傳下載文件

做法是使用多線程, 非NIO版本

服務(wù)端程序3

package com.loyotech.bigscreenbackend.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @program big-screen-backend
 * @description 支持多用戶下載文件
 * @author Rudolph Browne
 * @create 19-1-12
 */
public class ServerSocket3 {
    public static void main(String[] args) throws IOException {

        // 暴露服務(wù), 端點(diǎn)地址: 本機(jī)IP和8888
        try(ServerSocket server = new ServerSocket(8888)){

            while (true) {
                Socket socket = server.accept();
                System.out.println("與客戶端 " + socket.getInetAddress().getHostAddress() + " 連接成功...");
                new Thread(new MyDownloadFileSocketHelper(socket,
                        new File("/home/harry/Desktop/Spring揭秘.pdf"))).start();
            }
        }


    }

    /**
     * 發(fā)送1M的消息
     * @param socket
     * @param fileDescriptor
     * @throws IOException
     */
    private static void sendFile(Socket socket, File fileDescriptor) throws IOException {

        try(FileInputStream fileInputStream = new FileInputStream(fileDescriptor)) {

            OutputStream packageOut = socket.getOutputStream();

            byte[] buf = new byte[1024]; // 1M大小的緩沖區(qū)
            int len = -1; // 每次讀文件流大小

            while((len = fileInputStream.read(buf)) != -1) {
                packageOut.write(buf, 0, len);
            }

            System.out.println("成功將文件"+ fileDescriptor.getAbsolutePath()
                    + "發(fā)送至" + socket.getInetAddress().getHostAddress());

            socket.shutdownOutput();
        }

    }

    private static class MyDownloadFileSocketHelper implements Runnable {

        private Socket socket;
        private File fileDescriptor;

        public MyDownloadFileSocketHelper(Socket socket, File fileDescriptor){
            this.socket = socket;
            this.fileDescriptor = fileDescriptor;
        }

        @Override
        public void run() {
            try {
                sendFile(socket, fileDescriptor);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

客戶端程序3

package com.loyotech.bigscreenbackend.socket;

import java.io.*;
import java.net.Socket;
import java.time.Instant;

/*
 * @program big-screen-backend
 * @description 支持多用戶下載文件
 * @author Rudolph Browne
 * @create 19-1-12
 */
public class ClientSocket3 {
    public static void main(String[] args) throws IOException {

        try(Socket socket = new Socket("192.168.0.104", 8888)) {

            acceptFile(socket, new File("/media/harry/OS/Users/Rudolph Browne/WorkingSpace/揭秘" + Instant.now() + ".pdf"));
        }
    }

    /**
     * 讀取1M數(shù)據(jù)量的消息
     * @param socket
     * @throws IOException
     */
    private static void acceptFile(Socket socket, File fileDescriptor) throws IOException {
        try(FileOutputStream fileOutputStream = new FileOutputStream(fileDescriptor)) {
            InputStream pacakageIn = socket.getInputStream();
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = pacakageIn.read(buf)) != -1){
                fileOutputStream.write(buf, 0, len);
            }
            socket.shutdownInput();
        }
        System.out.println("從" + socket.getInetAddress().getHostAddress() + "接收數(shù)據(jù)," +
                "數(shù)據(jù)寫入成功,存儲(chǔ)位置: " + fileDescriptor.getAbsolutePath());
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末菇民,一起剝皮案震驚了整個(gè)濱河市尽楔,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌第练,老刑警劉巖阔馋,帶你破解...
    沈念sama閱讀 211,561評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異娇掏,居然都是意外死亡呕寝,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,218評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門婴梧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)下梢,“玉大人客蹋,你說(shuō)我怎么就攤上這事∧踅” “怎么了讶坯?”我有些...
    開(kāi)封第一講書(shū)人閱讀 157,162評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)岗屏。 經(jīng)常有香客問(wèn)我辆琅,道長(zhǎng),這世上最難降的妖魔是什么这刷? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,470評(píng)論 1 283
  • 正文 為了忘掉前任婉烟,我火速辦了婚禮,結(jié)果婚禮上崭歧,老公的妹妹穿的比我還像新娘隅很。我一直安慰自己撞牢,他們只是感情好率碾,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,550評(píng)論 6 385
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著屋彪,像睡著了一般所宰。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上畜挥,一...
    開(kāi)封第一講書(shū)人閱讀 49,806評(píng)論 1 290
  • 那天仔粥,我揣著相機(jī)與錄音,去河邊找鬼蟹但。 笑死躯泰,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的华糖。 我是一名探鬼主播麦向,決...
    沈念sama閱讀 38,951評(píng)論 3 407
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼客叉!你這毒婦竟也來(lái)了诵竭?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,712評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤兼搏,失蹤者是張志新(化名)和其女友劉穎卵慰,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體佛呻,經(jīng)...
    沈念sama閱讀 44,166評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡裳朋,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,510評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了吓著。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鲤嫡。...
    茶點(diǎn)故事閱讀 38,643評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡氧苍,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出泛范,到底是詐尸還是另有隱情让虐,我是刑警寧澤,帶...
    沈念sama閱讀 34,306評(píng)論 4 330
  • 正文 年R本政府宣布罢荡,位于F島的核電站赡突,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏区赵。R本人自食惡果不足惜惭缰,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,930評(píng)論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望笼才。 院中可真熱鬧漱受,春花似錦、人聲如沸骡送。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,745評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)摔踱。三九已至虐先,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間派敷,已是汗流浹背蛹批。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,983評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留篮愉,地道東北人腐芍。 一個(gè)月前我還...
    沈念sama閱讀 46,351評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像试躏,于是被迫代替她去往敵國(guó)和親猪勇。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,509評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,309評(píng)論 0 10
  • 呂小鍵閱讀 393評(píng)論 8 5
  • 十年冗酿,說(shuō)長(zhǎng)不長(zhǎng)埠对,說(shuō)短也不短,這是一段屬于我們愛(ài)情長(zhǎng)跑的時(shí)光裁替。十年我們從陌生人项玛,一路走來(lái),經(jīng)歷的分分秒秒都那么...
    嘎鵬閱讀 430評(píng)論 0 1
  • 雨弱判,滑落逝去的時(shí)光 我看見(jiàn)過(guò)往的落寞 淚流滿面 風(fēng)襟沮,吹起琉璃的年華 我看見(jiàn)遠(yuǎn)方的夢(mèng)想 淚流滿面 雨,風(fēng),心變的慢了...
    安清兒閱讀 188評(píng)論 1 3
  • 每個(gè)人的青春里,都會(huì)有好多個(gè)人走進(jìn)來(lái)固灵,又會(huì)有很多人走出去捅伤,這個(gè)善變的世界里,幸好有你的陪伴巫玻,讓我在磕磕絆絆中感受到...
    艾滌生微習(xí)慣3650天閱讀 817評(píng)論 2 1