本文使用socket的长连接,进行消息的发送和接受。
1、两端
client 端,server端
2、两线程
客户端、服务器端,各开两个线程,实现读写,可以全双工通信,异步发送,异步接受。
3、两注意
1)程序等待输入和一直处于等待消息发来,所以,用到死循环;同时,避免使用socket.close();
否则报异常:java.net.SocketException: socket closed
2)读消息,用到的是行读,nextLine()方法,所以,一定要在发送消息时,在消息末尾追加加上换行符,否则读不到。
代码:
1、消息发送服务类
package com.socket.newChat; import java.io.IOException; import
java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; /** *
Created by Liuxd on 2018-09-15. */ public class SendMessageService implements
Runnable { private Socket socket; private String name; public
SendMessageService(Socket socket, String name) { this.socket = socket;
this.name = name; } public void run() { PrintWriter pWriter = null; Scanner
scanner = null; try { pWriter = new PrintWriter(socket.getOutputStream());
scanner = new Scanner(System.in); while (true) { String s = scanner.nextLine();
pWriter.write(name + s + "\n"); pWriter.flush(); } } catch (IOException e) {
e.printStackTrace(); } finally { scanner.close(); pWriter.close(); } } }
2、消息接受服务类
package com.socket.newChat; import java.io.IOException; import
java.net.Socket; import java.util.Scanner; /** * Created by Liuxd on
2018-09-15. */ public class ReceiveMessageService implements Runnable { private
Socket socket; public ReceiveMessageService(Socket socket) { this.socket =
socket; } @Override public void run() { Scanner scanner = null; try { scanner =
new Scanner(socket.getInputStream()); while (scanner.hasNext()) {
System.out.println(scanner.nextLine()); } } catch (IOException e) {
e.printStackTrace(); } finally { scanner.close(); } } }
3、服务端
package com.socket.newChat; /** * Created by Liuxd on 2018-09-15. */ import
java.io.IOException; import java.net.ServerSocket; import java.net.Socket;
public class TestServer { public static void main(String[] args) throws
IOException { ServerSocket serverSocket = new ServerSocket(8081); while (true)
{ Socket socket=serverSocket.accept(); new Thread(new
SendMessageService(socket,"服务器端:")).start(); new Thread(new
ReceiveMessageService(socket)).start(); System.out.println("请输入..."); } } }
4、客户端
package com.socket.newChat; /** * Created by Liuxd on 2018-09-15. */ import
java.io.IOException; import java.net.Socket; import
java.net.UnknownHostException; public class TestClient { public static void
main(String[] args) { try { Socket socket = new Socket("127.0.0.1", 8081); new
Thread(new SendMessageService(socket,"客户端:")).start(); new Thread(new
ReceiveMessageService(socket)).start(); System.out.println("请输入..."); } catch
(UnknownHostException e) { e.printStackTrace(); } catch (IOException e) {
e.printStackTrace(); } } }
热门工具 换一换