Java 网络编程二---防QQ简单聊天

更详细网络知识请点击这里


话不多说先看两张截图


直接粘代码

服务器端

package com.fy.tcp_socket;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;

public class MyServer extends JFrame implements Runnable{
    private ServerSocket serverSocket;
    private Socket socket;
    private BufferedReader br;
    private PrintWriter writer;
    private JTextArea ta = new JTextArea();
    private JTextField tf = new JTextField();
    Container cc;

    public MyServer(String title) {
        super(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        cc = this.getContentPane();

        final JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBorder(new BevelBorder(BevelBorder.RAISED));
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        scrollPane.setViewportView(ta);
        cc.add(tf, "South");

        tf.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                writer.println(tf.getText());
                ta.append("我说(服务器):" + tf.getText() + '\n');
                ta.setSelectionEnd(ta.getText().length());
                tf.setText("");
            }
        });
    }

    public void getServer() {
        try {
            serverSocket = new ServerSocket(6666);
            ta.append("服务器开启成功\n");
            ta.append("等待客户端连接\n");
            while (true) {
                socket = serverSocket.accept();
                sendClientMessage();// 发消息一定要先收消息前声明
                getClientMessage();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getClientMessage() {
        try {
            br = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            while (true) {
                ta.append("客户端说:" + br.readLine() + '\n');
                ta.setSelectionEnd(ta.getText().length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (br != null) {
                br.close();
            }
            if (writer != null) {
                writer.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendClientMessage() {
        try {
            writer = new PrintWriter(socket.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyServer server = new MyServer("Server");
        server.setSize(300, 300);
        server.setVisible(true);
        server.getServer();
    }

    @Override
    public void run() {
        
    }

}

客户端

package com.fy.tcp_socket;

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

import javax.swing.*;
import javax.swing.border.*;

public class MyClient extends JFrame {

    private static final long serialVersionUID = 1L;
    private PrintWriter writer;
    private BufferedReader br;
    Socket socket;
    private JTextArea ta = new JTextArea();
    private JTextField tf = new JTextField();
    Container cc;

    public MyClient(String title) {
        super(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        cc = this.getContentPane();

        final JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBorder(new BevelBorder(BevelBorder.RAISED));
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        scrollPane.setViewportView(ta);
        cc.add(tf, "South");
        tf.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                writer.println(tf.getText());

                ta.append("我说(客户端):" + tf.getText() + '\n');
                ta.setSelectionEnd(ta.getText().length());
                tf.setText("");
            }
        });
    }

    private void connect() {
        ta.append("尝试连接\n");
        try {
            socket = new Socket("localhost", 6666);
            writer = new PrintWriter(socket.getOutputStream(), true);
            ta.append("完成连接\n");
            br = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            getServerMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getServerMessage() {
        try {
            while (true) {
                ta.append("服务器说:"+br.readLine()+'\n');
                ta.setSelectionEnd(ta.getText().length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }try {
            if (br != null) {
                br.close();
            }
            if (writer != null) {
                writer.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyClient client1 = new MyClient("Client");
        client1.setSize(300,300);
        client1.setVisible(true);
        client1.connect();
    }
}

你可能感兴趣的:(Java 网络编程二---防QQ简单聊天)