项目-使用Socket写网络通信软件

最近实训讲了Socket通信机制,实战了一个利用Socket监听端口,客户端连接端口来实现通信的项目

项目demo

主要利用线程来处理通信

多台客户端连接的话需要使用线程池来解决,暂时先不写着呢(主要是还是不太熟悉~~~~(>_<)~~~~ )

服务器端代码实现

package net.b521.Freakboy.Socket;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;


/**
 * @author Freakboy
 * @param args
 */


public class Server extends JFrame implements ActionListener {
    
    JPanel contentPane;
    JLabel jLabel2 = new JLabel();
    JTextField jTextField2 = new JTextField("8000");
    JButton jButton1 = new JButton();
    JLabel jLabel3 = new JLabel();
    JTextField jTextField3 = new JTextField();
    JButton jButton2 = new JButton();
    JScrollPane JScrollPane1 = new JScrollPane();
    JTextArea jTextArea1 = new JTextArea();
    ServerSocket server = null;
    Socket socket = null;
    BufferedReader instr = null;
    PrintWriter os = null;
    //构造框架
    
    public Server() {
        jbInit();
    }
    
    //创建线程
    class MyThread extends Thread{
        @Override
        public void run() {
            try {
                
                while (true) {
                    this.sleep(100);
                    instr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    
                    if (instr.ready()) {     //检查是否有数据
                        
                        jTextArea1.append("客户端:"+instr.readLine()+"\n");
                    }
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
    @Override
    public void actionPerformed(ActionEvent e) {
        
        if (e.getSource() == jButton1) {
            int port = Integer.parseInt(jTextField2.getText().trim());
            listenClient(port);
        }
        if (e.getSource() == jButton2) {
            String s = this.jTextField3.getText().trim();
            sendData(s);
        }
    }
    
    
    private void listenClient(int port) {   //监听
        try {
            
            if (jButton1.getText().trim().equals("监听")) {
                server =new ServerSocket(port);
                jButton1.setText("正在监听...");
                
                //等待,直到有客户端连接才往下执行
                socket = server.accept();
                
                sendData("已经成功连接...");
                jButton1.setText("正在聊天...");
                jTextArea1.append("客户端已经连接到服务器\n");
                MyThread t = new MyThread();
                t.start();//线程启动
                
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    private void sendData(String s) {   //发送数据
        try {
            
            os = new PrintWriter(socket.getOutputStream());
            os.println(s);
            os.flush();//强制输出缓冲区中所有的内容
            if(!s.equals("已经成功连接..."))
                this.jTextArea1.append("Server:"+ s + "\n");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    //界面设计
    private void jbInit() {
        contentPane = (JPanel)this.getContentPane();
        contentPane.setLayout(null);
        this.setSize(new Dimension(540,340));
        this.setTitle("服务器");
        jLabel2.setBounds(new Rectangle(22, 27, 72, 28));
        jLabel2.setText("端口号");
        jLabel2.setFont(new java.awt.Font("宋体",0,14));
        jTextField2.setBounds(new Rectangle(113, 27, 315, 24));
        
        jButton1.setBounds(new Rectangle(440, 28, 73, 25));
        jButton1.setFont(new java.awt.Font("Dialog",0,14));
        jButton1.setBorder(BorderFactory.createEtchedBorder());
        jButton1.setActionCommand("jButton1");
        jButton1.setText("监听");
        jLabel3.setBounds(new Rectangle(23, 57, 87, 28));
        jLabel3.setText("请输入信息:");
        jLabel3.setFont(new java.awt.Font("宋体", 0, 14));
        
        jTextField3.setBounds(new Rectangle(114, 60, 314, 24));
        jTextField3.setText("");
        jButton2.setText("发送");
        jButton2.setActionCommand("jButton1");
        jButton2.setBorder(BorderFactory.createEtchedBorder());
        jButton2.setFont(new java.awt.Font("Dialog", 0, 14));
        jButton2.setBounds(new Rectangle(440,58,73,25));
        JScrollPane1.setBounds(new Rectangle(23, 92, 493, 189));
        
        contentPane.add(jTextField2,null);
        contentPane.add(jButton1, null);
        contentPane.add(jLabel3, null);
        contentPane.add(jTextField3, null);
        contentPane.add(jButton2, null);
        contentPane.add(JScrollPane1, null);
        contentPane.add(jLabel2, null);
        JScrollPane1.getViewport().add(jTextArea1, null);
        //注册监听器
        jButton1.addActionListener(this);
        jButton2.addActionListener(this);
        //关闭socket
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                try {
                    
                    socket.close();
                    instr.close();
                    System.exit(0);
                    
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        });
        
    }
    
    
    
    public static void main(String[] args) {
        
        JFrame.setDefaultLookAndFeelDecorated(true);
        Server frm = new Server();
        frm.setVisible(true);
        
    }




}

客户端代码实现

package net.b521.Freakboy.Socket;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;

/**
 * @author Freakboy
 * @param args
 */

public class Client extends JFrame implements ActionListener {

    JPanel contentPane;
    JLabel jLabel1 = new JLabel();
    //可自定义地址,本地,局域网,Web
    JTextField jTextField1 = new JTextField("127.0.0.1");
    JLabel jlLabel2 = new JLabel();
    //指定端口
    JTextField jTextField2 = new JTextField("8000");
    JButton jButton1 = new JButton();
    JLabel jLabel3 = new JLabel();
    JTextField jTextField3 = new JTextField();
    JButton jButton2 = new JButton();
    JScrollPane jScrollPane1 = new JScrollPane();
    JTextArea jTextArea1 = new JTextArea();
    BufferedReader instr = null;
    Socket socket = null;
    PrintWriter os = null;
    public Client() {
        jbInit();
    }
    
    
    class MyThread extends Thread{
        @Override
        public void run() {
            try {
                
                os = new PrintWriter(socket.getOutputStream());
                instr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                
                while (true) {
                    this.sleep(100);//休眠0.1秒
                    if (instr.ready()) {
                        jTextArea1.append("服务器:" + instr.readLine() + "\n");
                    }
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jButton1) {
            String ip = jTextField3.getText().trim();
            int port =Integer.parseInt(jTextField2.getText().trim());
            connectServer(ip,port);
        }
        
        if (e.getSource() == jButton2) {
            String s = this.jTextField3.getText().trim();
            sendData(s);
        }
        
    }
    
    
    private void connectServer(String ip, int port) {   //连接
        
        try {
            
            if (jButton1.getText().trim().equals("连接")) {
                jButton1.setText("连接服务器...");
                socket = new Socket(ip, port);
                jButton1.setText("正在聊天");
                
                MyThread t = new MyThread();
                t.start();
                
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    
    private void sendData(String s) {   //发送数据
        
        try {
            
            os = new PrintWriter(socket.getOutputStream());
            os.println(s);
            
            os.flush();//强制输出
            this.jTextArea1.append("Server:" + s + "\n");
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    
    //界面初始化设计
    private void jbInit() {
        contentPane = (JPanel)this.getContentPane();
        jLabel1.setFont(new java.awt.Font("宋体", 0, 14));
        jLabel1.setText("服务器名称:");
        jLabel1.setBounds(new Rectangle(20, 22, 87, 28));
        contentPane.setLayout(null);
        this.setSize(new Dimension(540, 340));
        this.setTitle("客户端");
        
        jTextField1.setBounds(new Rectangle(114, 26, 108, 24));
        jlLabel2.setBounds(new Rectangle(250, 25, 75, 28));
        jlLabel2.setText("端口号");
        jlLabel2.setFont(new java.awt.Font("宋体", 0, 14));
        jTextField2.setBounds(new Rectangle(320, 27, 108, 24));
        jButton1.setBounds(new Rectangle(440, 28, 73, 25));
        jButton1.setFont(new java.awt.Font("Dialog", 0, 14));
        jButton1.setBorder(BorderFactory.createEtchedBorder());
        jButton1.setActionCommand("jButton1");
        jButton1.setText("连接");
        jLabel3.setBounds(new Rectangle(23, 57, 87, 28));
        jLabel3.setText("请输入信息:");
        jLabel3.setFont(new java.awt.Font("宋体", 0, 14));
        jTextField3.setBounds(new Rectangle(114, 60, 314, 24));
        
        jButton2.setText("发送");
        jButton2.setActionCommand("jButton1");
        jButton2.setBorder(BorderFactory.createEtchedBorder());
        jButton2.setFont(new java.awt.Font("Dialog", 0, 14));
        jButton2.setBounds(new Rectangle(440, 58, 73, 25));
        jScrollPane1.setBounds(new Rectangle(23, 92, 493, 189));
        
        contentPane.add(jLabel1, null);
        contentPane.add(jTextField1, null);
        contentPane.add(jlLabel2, null);
        contentPane.add(jTextField2, null);
        contentPane.add(jButton1, null);
        contentPane.add(jLabel3, null);
        contentPane.add(jTextField3, null);
        contentPane.add(jButton2, null);
        contentPane.add(jScrollPane1, null);
        jScrollPane1.getViewport().add(jTextArea1, null);
        jButton1.addActionListener(this);
        jButton2.addActionListener(this);
        this.addWindowListener(new WindowAdapter() {
            
            @Override
            public void windowClosing(WindowEvent e) {
                try {
                    
                    socket.close();
                    instr.close();
                    os.close();
                    System.exit(0);
                    
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            
        });
        
        
        
    }
    
    
    public static void main(String[] args) {
        
        JFrame.setDefaultLookAndFeelDecorated(true);
        Client frm = new Client();
        frm.setVisible(true);
        
    }

}

总结

使用Socket 监听指定端口,客户端连接成功后,在服务器和客户端之间就形成了一条通道,就可以使用Socket类的getInputStream()和getOutputStream()来读写信息了。

最后由 不一样的少年 编辑于2016年06月15日 23:38