同时收发消息
这是因为接受和发送都在主线程中,不能同时进行。 为了实现同时收发消息,基本设计思路是把收发分别放在不同的线程中进行
1. SendThread 发送消息线程
2. RecieveThread 接受消息线程
3. Server一旦接受到连接,就启动收发两个线程
4. Client 一旦建立了连接,就启动收发两个线程
1. SendThread 发送消息线程
2. RecieveThread 接受消息线程
3. Server一旦接受到连接,就启动收发两个线程
4. 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
|
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; } 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) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
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
|
package socket; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.Scanner; public class RecieveThread extends Thread { private Socket s; public RecieveThread(Socket s) { this .s = s; } public void run() { try { InputStream is = s.getInputStream(); DataInputStream dis = new DataInputStream(is); while ( true ) { String msg = dis.readUTF(); System.out.println(msg); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
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.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) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
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
|
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) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |