服务器之家

服务器之家 > 正文

Java网络编程实现多线程聊天

时间:2021-09-26 00:44     来源/作者:大唐雨夜
本文实例为大家分享了Java网络编程实现多线程聊天的具体代码,供大家参考,具体内容如下

聊天程序如果是单线程,会导致没人只能说一句,并且说了以后,必须等到另一个人的回复,才能说第二句。收发都在主线程中,不能同时进行。

解决方法:

将收发放到两个不同的线程

1. SendThread 发送消息线程
2. RecieveThread 接受消息线程
3. Server一旦接受到连接,就启动收发两个线程
4. Client 一旦建立了连接,就启动收发两个线程

多线程聊天

1 SendThread

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package socket;
 
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
 
public class SendThread extends Thread {
    private Socket s;
    public SendThread(Socket s) {
        this.s = s;
    }
    @Override
    public void run() {
        try {
            OutputStream os = s.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            while(true){
                Scanner sc = new Scanner(System.in);
                String str = sc.next();
                dos.writeUTF(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2 RecieveThread

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package socket;
 
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
 
public class RecieveThread extends Thread {
    private Socket s;
    public RecieveThread(Socket s) {
        this.s = s;
    }
    @Override
    public void run() {
        InputStream is = null;
        try {
            is = s.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            while(true){
                String msg = dis.readUTF();
                System.out.println(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
 
}

3 Server

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package socket;
 
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(8888);
            System.out.println("监听端口号:8888");
            Socket s = ss.accept();
 
            new SendThread(s).start();
            new RecieveThread(s).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4 Client

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package socket;
 
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
 
public class Client {
    public static void main(String[] args) {
        try {
            Socket s = new Socket("127.0.0.1", 8888);
 
            new SendThread(s).start();
            new RecieveThread(s).start();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

简单对话框

Server

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package socket;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
public class GUIServer {
 
    public static void main(String[] args) throws Exception {
 
        JFrame f = new JFrame();
        f.setTitle("server");
 
        f.setSize(400, 300);
        f.setLocation(100, 200);
        f.setLayout(null);
 
        JButton b = new JButton("send");
        b.setBounds(10, 10, 80, 30);
        f.add(b);
 
        final JTextField tf = new JTextField();
        tf.setBounds(10, 110, 80, 30);
        f.add(tf);
 
        final JTextArea ta = new JTextArea();
        ta.setBounds(110,10, 200, 300);
        f.add(ta);
 
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
 
        ServerSocket ss = new ServerSocket(8888);
 
        System.out.println("listenning on port:8888");
        final Socket s =  ss.accept();       
        new Thread() {
            public void run() {
                while (true) {
                    try {
                        DataInputStream dis = new DataInputStream(
                                s.getInputStream());
                        String text = dis.readUTF();
                        ta.append(text+"\r\n");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
 
            }
        }.start();
 
        b.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
 
                String text = tf.getText();
                ta.append(text+"\r\n");
 
                try {
                    DataOutputStream dos = new DataOutputStream(
                            s.getOutputStream());
                    dos.writeUTF(text);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
 
    }
}

Client

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package socket;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
public class GUIClient {
 
    public static void main(String[] args) throws Exception {
 
        JFrame f = new JFrame();
        f.setTitle("client");
 
        f.setSize(400, 300);
        f.setLocation(600, 200);
        f.setLayout(null);
 
        JButton b = new JButton("send");
        b.setBounds(10, 10, 80, 30);
        f.add(b);
 
        final JTextField tf = new JTextField();
        tf.setBounds(10, 110, 80, 30);
        f.add(tf);
 
        final JTextArea ta = new JTextArea();
        ta.setBounds(110,10, 200, 300);
        f.add(ta);
 
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
 
        final Socket s = new Socket("127.0.0.1", 8888);
 
        new Thread() {
            public void run() {
                while (true) {
                    try {
                        DataInputStream dis = new DataInputStream(
                                s.getInputStream());
                        String text = dis.readUTF();
                        ta.append(text+"\r\n");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
 
            }
        }.start();
 
        b.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(ActionEvent e) {
 
                String text = tf.getText();
                ta.append(text+"\r\n");
 
                try {
                    DataOutputStream dos = new DataOutputStream(
                            s.getOutputStream());
                    dos.writeUTF(text);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
 
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/LIZHONGPING00/article/details/65437684

标签:

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
返回顶部