• Java Socket基础[备忘]


    1.服务端----Server.java

       

    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    /**
     * Created by JXJ on 2017/6/26.
     */
    public class Server extends JFrame{
    
        private JTextField userText;
        private JTextArea chatWindow;
        private ObjectOutputStream output;
        private ObjectInputStream input;
        private ServerSocket server;
        private Socket connection;
        //构造方法
        public Server(){
            super("即时聊天小程序");
            userText=new JTextField();
            userText.setEditable(false);
            userText.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    sendMessage(e.getActionCommand());
                    userText.setText("");
                }
            });
            add(userText,BorderLayout.NORTH);
            chatWindow=new JTextArea();
            add(new JScrollPane(chatWindow));
            setSize(300,150);
            setVisible(true);
    
        }
    
    
    
        //建立并启动服务
        public void startRununing(){
            try{
                server=new ServerSocket(6789,100);
                while(true){
                    try{
                        //等待连接
                        waitForConnect();
                        //获取输入输出数据流
                        setupStreams();
                        //聊天
                        whileChatting();
                    }catch (EOFException eofException){
                            showMessage("
     连接已经结束!");
                    }finally {
                        closeCrap();
                    }
                }
            }catch (IOException ioException){
                ioException.printStackTrace();
            }
        }
    
    
    
        //等待连接,然后显示连接信息
        private void waitForConnect()  throws IOException{
            showMessage(" 等待客户端连接...
    ");
            connection=server.accept();
            showMessage("客户端"+connection.getInetAddress().getHostName()+"已连接!
     ");
        }
    
        //获取输入输出流
        private void setupStreams() throws IOException{
            output=new ObjectOutputStream(connection.getOutputStream());
            //这个重点关注一下
            output.flush();
            input=new ObjectInputStream(connection.getInputStream());
            showMessage("
    数据流已建立!
     ");
        }
        //聊天信息处理
        private void whileChatting() throws IOException {
            String message="现在你已经连接上了!";
            sendMessage(message);
            ableToType(true);
            do{
                try{
                    message=(String)input.readObject();
                    showMessage(message+"
     ");
                }catch (ClassNotFoundException classNotFoundException){
                    showMessage("用户发送信息转换异常!
    ");
                }
            }while(!message.equals("client-end"));
    
        }
        //聊天结束后关闭输入输出流和socket
        private void closeCrap() {
            showMessage("正在关闭连接...
    ");
            ableToType(false);
            try{
                //注意关闭先后顺序   输出流  输入流  socket
                output.close();
                input.close();
                connection.close();
            }catch (IOException ioException){
    
            }
        }
    
        //给客户端发送信息
        private void sendMessage(String message) {
            try{
                output.writeObject("Server"+message);
                output.flush();
                showMessage("Server"+message+"
    ");
            }catch (IOException ioException){
                chatWindow.append("[错误] 我没有成功发送信息!");
            }
        }
        //在窗口上实时显示聊天信息
        private void showMessage(final String text) {
            //注意窗口更新信息的方式
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    chatWindow.append(text);
                }
            });
        }
        //让用户输入信息
        private void ableToType(final boolean tof) {
            //注意按钮的禁用与启用的方式
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    userText.setEditable(tof);
                }
            });
        }
    }

    2.服务端测试----ServerTest.java

    /**
     * Created by JXJ on 2017/6/26.
     */
    import javax.swing.JFrame;
    public class ServerTest {
        public static  void main(String[] args){
            Server server=new Server();
            server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            server.startRununing();
        }
    }
    

      

       

    3.客户端----Client.java

    /**
     * Created by JXJ on 2017/6/26.
     */
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Client extends JFrame {
        private JTextField userText;
        private JTextArea chatwindow;
        private ObjectInputStream input;
        private ObjectOutputStream output;
        private String message="";
        private String serverIP;
        private Socket connection;
    
        //构造方法
        public Client(String host){
            super("客户端");
            serverIP=host;
            userText=new JTextField();
            userText.setEditable(false);
            userText.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    sendMessage(e.getActionCommand());
                    userText.setText("");
                }
            });
            add(userText,BorderLayout.NORTH);
            chatwindow=new JTextArea();
            add(new JScrollPane(chatwindow),BorderLayout.CENTER);
            setSize(300,150);
            setVisible(true);
    
        }
        //建立连接
        public void startRununing(){
            try{
                connectToServer();
                setupStreams();
                whileChatting();
            }catch (EOFException eofException){
                    showMessage("客户端断开连接! 
    ");
            }catch (IOException ioExceptiopn){
                    ioExceptiopn.printStackTrace();
            }
            finally {
                closeCrap();
            }
        }
    
        //连接到服务端
        private void connectToServer() throws IOException {
            showMessage("正在尝试连接服务端... 
    ");
            connection=new Socket(InetAddress.getByName(serverIP),6789);
            showMessage("已连接至"+connection.getInetAddress().getHostName());
        }
    
        //建立输入输出流
        private void setupStreams() throws IOException {
            output=new ObjectOutputStream(connection.getOutputStream());
            output.flush();
            input=new ObjectInputStream(connection.getInputStream());
            showMessage("已创建输入输出流... 
    ");
        }
        //聊天信息处理
        private void whileChatting() throws IOException {
            ableToType(true);
            do{
                try{
                    message=(String)input.readObject();
                    showMessage(message+"
    ");
                }catch (ClassNotFoundException classNotFoundException){
                    showMessage(" 未知的输入对象类型
    ");
                }
            }while(!message.equals("server-end"));
        }
        //关闭输入输出流和socket
        private void closeCrap() {
            showMessage("关闭客户端连接资源
    ");
            ableToType(false);
            try{
                output.close();
                input.close();
                connection.close();
            }catch (IOException ioException){
                ioException.printStackTrace();
            }
        }
        //给服务端发送信息
        private void sendMessage(String message) {
            try{
                output.writeObject("client-"+message);
                output.flush();
                showMessage("client-"+message+"
    ");
            }catch (IOException ioException){
                showMessage("客户端发送数据失败
    ");
            }
        }
        //在窗口上实时显示聊天信息
        private void showMessage(final String text) {
            //注意窗口更新信息的方式
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    chatwindow.append(text);
                }
            });
        }
        //让用户输入信息
        private void ableToType(final boolean tof) {
            //注意按钮的禁用与启用的方式
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    userText.setEditable(tof);
                }
            });
        }
    }
    

      

    4.客户端测试----ClientTest.java

    import javax.swing.*;
    
    /**
     * Created by JXJ on 2017/6/26.
     */
    public class ClientTest {
        public static  void main(String[] args){
            Client client=new Client("127.0.0.1");
            client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            client.startRununing();
        }
    }
    

      

    【路漫漫其修远兮,吾将上下而求索】

  • 相关阅读:
    SpringBoot如何使用WebSocket实现前后端交互
    httpx的两个坑(httpx.ReadTimeout; SSL: CERTIFICATE_VERIFY_FAILED)
    力扣744:寻找比目标字母大的最小字母; LeetCode744:Find Smallest Letter Greater Than Target
    【案例】invalid primary checkpoint record
    PG Wal 日志清理
    搭建Grafana+Prometheus监控平台
    一个简单的Dockerfile多阶段构建go项目
    gin框架中的c.Next()/c.Abort()
    java中 抽象类和接口的区别, 什么时候用抽象类?什么时候用接口?
    JetBrains激活和无限试用
  • 原文地址:https://www.cnblogs.com/binghuojxj/p/7096459.html
Copyright © 2020-2023  润新知