java Socket编程(tcp篇)

概述

关于网络的基础知识,请自行google,这里通过socket(tcp)来实现一个简单的对话。

Tcp协议的Socket

服务端四步走:
1.创建服务端socket并绑定端口号
2.开始监听
3.读取客户端信息
4.向客户端发送信息

package tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            // 1.创建服务端socket并绑定端口号
            serverSocket = new ServerSocket(8888);// 系统占用的端口号0-1024
            // 2.开始监听
            System.out.println("******************开始监听****************");
            while (true) {// 死循环,持续监听
                Socket socket = serverSocket.accept();// 进入阻塞状态,等待客户端连接
                HandleThread handleThread = new HandleThread(socket);// 有客户端连接则新启一个线程来处理
                handleThread.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理客户端连接的线程
     * 
     * @author xiao
     *
     */
    static class HandleThread extends Thread {
        private BufferedReader br;
        private InputStreamReader isr;
        private InputStream is;
        private OutputStream os;
        private OutputStreamWriter osw;
        private BufferedWriter bw;
        private Socket mSocket;

        public HandleThread(Socket socket) {
            mSocket = socket;
        }

        @Override
        public void run() {
            // 3.读取客户端信息
            try {
                is = mSocket.getInputStream();
                isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                System.out.println("客户端说:" + sb);
                // 4.向客户端发送信息
                os = mSocket.getOutputStream();
                osw = new OutputStreamWriter(os);
                bw = new BufferedWriter(osw);
                bw.write("hello,我是服务端");
                bw.flush();
                mSocket.shutdownOutput();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 释放资源
                try {
                    if (bw != null) {
                        bw.close();
                    }
                    if (osw != null) {
                        osw.close();
                    }
                    if (os != null) {
                        os.close();
                    }
                    if (br != null) {
                        br.close();
                    }
                    if (isr != null) {
                        isr.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                    if (mSocket!=null) {
                        mSocket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

客户端三步走:
1.创建socket连接
2.向服务端发送消息
3.读取服务端消息

package tcp;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class Client {

    public static void main(String[] args) {
        OutputStream os= null;
        OutputStreamWriter osw= null;
        BufferedWriter bw= null;
        InputStream is= null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        Socket socket= null;
        try {
            // 1.创建socket连接 地址-->localhost:8888
            socket = new Socket("localhost", 8888);
            System.out.println("******************客户端连接服务端***********************");
            // 2.向服务端发送消息
            os = socket.getOutputStream();
            osw = new OutputStreamWriter(os);
            bw = new BufferedWriter(osw);
            bw.write("hello,我是客户端"+(int)(Math.random()*100));//用随机数模拟不同客户端请求服务器
            bw.flush();
            socket.shutdownOutput();
            // 3.读取服务端消息
            is = socket.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println("服务端说:" + sb);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (is != null) {
                    is.close();
                }
                if (bw != null) {
                    bw.close();
                }
                if (osw != null) {
                    osw.close();
                }
                if (os != null) {
                    os.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

测试一下

先启动服务端,再启动客户端(多次启动,模拟多用户访问服务器)

服务端打印:


java Socket编程(tcp篇)_第1张图片
image.png

客户端打印


java Socket编程(tcp篇)_第2张图片
image.png

你可能感兴趣的:(java Socket编程(tcp篇))