当前位置:   article > 正文

使用Java socket 简单实现实时通信,单聊,群聊功能_基于java实现的实时通讯仅单聊

基于java实现的实时通讯仅单聊
  1. 一对一单聊的实现:客户端带着发送方ID和接收方ID、信息发送给服务端,服务端从socket池中找出接收方ID进行转发。
  2. 群发的实现:客户端发送群发消息给服务端,然后服务端从socket池中取出所有正在连接的客户端,然后进行转发
  1. import org.junit.Test;
  2. import java.io.*;
  3. import java.net.ServerSocket;
  4. import java.net.Socket;
  5. import java.net.SocketException;
  6. import java.util.HashMap;
  7. import java.util.UUID;
  8. public class socket {
  9. static java.util.Map<String, Socket> socketMap = new HashMap<>();
  10. public static void main(String[] args) throws InterruptedException {
  11. Thread server = new Thread(() -> {
  12. try {
  13. ServerSocket serverSocket = new ServerSocket(6666);
  14. while (true) {
  15. Socket socket = serverSocket.accept();
  16. serverRead(socket);
  17. }
  18. } catch (IOException e) {
  19. System.out.println("报错了");
  20. e.printStackTrace();
  21. }
  22. });
  23. server.join();
  24. server.start();
  25. mySocket b = clientConServer();
  26. mySocket a = clientConServer();
  27. try {
  28. clientSend(a,"你好",b.id);
  29. Thread.sleep(1000);
  30. clientSend(b,"你也好",a.id);
  31. Thread.sleep(1000);
  32. clientSendAll(a,"大家好");
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. Thread.sleep(1000);
  37. disconnect(a);
  38. Thread.sleep(1000);
  39. disconnect(b);
  40. try {
  41. a.socket.close();
  42. b.socket.close();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. /**
  48. * 客户端与服务端建立连接 C
  49. */
  50. public static mySocket clientConServer() {
  51. mySocket socket = new mySocket();
  52. try {
  53. PrintWriter printWriter = new PrintWriter(socket.socket.getOutputStream());
  54. printWriter.write("connect\n");
  55. printWriter.flush();
  56. printWriter.write(socket.id+"\n");
  57. printWriter.flush();
  58. readThread(socket.socket);
  59. } catch (IOException e) {
  60. e.printStackTrace();
  61. }
  62. return socket;
  63. }
  64. /**
  65. * 服务器监听 S
  66. */
  67. public static void serverRead(Socket socket) throws IOException {
  68. //开启服务器输入监听线程
  69. SocketInterface socketRead = (Socket socket1) -> {
  70. Thread thread = new Thread() {
  71. public Socket socket = socket1;
  72. String info;
  73. @Override
  74. public void run() {
  75. try {
  76. //获取输入流
  77. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
  78. while ((info = bufferedReader.readLine()) != null) {
  79. //如果监听到连接指令:connect,则获取socketId,并将此socket连接保存到静态map中
  80. if (info.equals("connect")) {
  81. //获取socketId
  82. String key = bufferedReader.readLine();
  83. //存入在静态Map中
  84. socketMap.put(key, socket);
  85. //回传给客户端,提示已经建立连接
  86. PrintWriter we = new PrintWriter(socket.getOutputStream());
  87. // System.out.println(key);
  88. we.write("客户端" + key + "连接服务器成功\n");
  89. we.flush();
  90. }
  91. //如果监听到连接指令:send,则获取发送客户端socketId:from,接受客户端socketId:to,发送的消息:message
  92. if ("send".equals(info)){
  93. //发送客户端socketId
  94. String from = bufferedReader.readLine();
  95. //接受客户端socketId
  96. String to = bufferedReader.readLine();
  97. //发送
  98. send(from,bufferedReader.readLine(),to);
  99. }
  100. //如果监听到连接指令:sendAll,则群发消息
  101. if ("sendAll".equals(info)){
  102. String from = bufferedReader.readLine();
  103. String message = bufferedReader.readLine();
  104. mass(message,from);
  105. }
  106. //如果监听到连接指令:disconnect,则断开与某个客户端的连接
  107. if ("disconnect".equals(info)){
  108. String from = bufferedReader.readLine();
  109. info = from;
  110. System.out.println(from+"请求断开连接");
  111. socketMap.get(from).getOutputStream().close();
  112. socketMap.get(from).getInputStream().close();
  113. socketMap.get(from).close();
  114. }
  115. // System.out.println(info);
  116. }
  117. } catch (SocketException se) {
  118. System.out.println(info+"已断开");
  119. } catch (IOException e) {
  120. e.printStackTrace();
  121. }
  122. }
  123. };
  124. thread.start();
  125. };
  126. socketRead.read(socket);
  127. }
  128. /**
  129. * 客户端接受信息 C
  130. *
  131. * @param socket
  132. */
  133. public static void readThread(Socket socket) {
  134. //开启客户端输入监听线程
  135. SocketInterface socketRead = (Socket socket1) -> {
  136. Thread thread = new Thread() {
  137. public Socket socket = socket1;
  138. public String info = null;
  139. @Override
  140. public void run() {
  141. try {
  142. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
  143. while ((info = bufferedReader.readLine()) != null) {
  144. System.out.println(info);
  145. }
  146. } catch (SocketException se) {
  147. System.out.println("socket关闭");
  148. } catch (IOException e) {
  149. e.printStackTrace();
  150. }
  151. }
  152. };
  153. thread.start();
  154. };
  155. socketRead.read(socket);
  156. }
  157. /**
  158. * 服务器转发群发消息 S
  159. *
  160. * @param message
  161. */
  162. public static void mass(String message, String fromUUID) {
  163. //遍历所有已连接服务器的socket
  164. socketMap.forEach((s, socket) -> {
  165. if (!socket.isClosed()) {
  166. try {
  167. // 发送信息
  168. PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
  169. printWriter.write( s+"收到来自<---"+fromUUID + "的群发消息:" + message + "\n");
  170. printWriter.flush();
  171. } catch (IOException e) {
  172. e.printStackTrace();
  173. }
  174. }
  175. });
  176. }
  177. /**
  178. * 客户端发送给客户端 C
  179. * @param a
  180. * @param message
  181. * @param to
  182. * @throws IOException
  183. */
  184. public static void clientSend(mySocket a,String message,String to) throws IOException {
  185. PrintWriter printWriter = new PrintWriter(a.socket.getOutputStream());
  186. printWriter.write("send\n");
  187. printWriter.flush();
  188. printWriter.write(a.id+"\n");
  189. printWriter.flush();
  190. printWriter.write(to+"\n");
  191. printWriter.flush();
  192. printWriter.write(message+"\n");
  193. printWriter.flush();
  194. }
  195. /**
  196. * 客户端群发消息 C
  197. *
  198. * @param a
  199. * @param message
  200. * @throws IOException
  201. */
  202. public static void clientSendAll(mySocket a,String message) throws IOException {
  203. PrintWriter printWriter = new PrintWriter(a.socket.getOutputStream());
  204. printWriter.write("sendAll\n");
  205. printWriter.flush();
  206. printWriter.write(a.id+"\n");
  207. printWriter.flush();
  208. printWriter.write(message+"\n");
  209. printWriter.flush();
  210. }
  211. /**
  212. * 服务器转发 S
  213. * @param from
  214. * @param message
  215. * @param to
  216. * @throws IOException
  217. */
  218. public static void send(String from,String message,String to) throws IOException {
  219. //从socket池中获取接受客户端socket,并写入信息
  220. PrintWriter printWriter = new PrintWriter(socketMap.get(to).getOutputStream());
  221. printWriter.write(to+"\n");
  222. printWriter.flush();
  223. printWriter.write(from+"发送给-->"+to+":"+message+"\n");
  224. printWriter.flush();
  225. }
  226. /**
  227. *
  228. * 断开连接 C
  229. */
  230. static void disconnect(mySocket mySocket){
  231. try {
  232. PrintWriter printWriter = new PrintWriter(mySocket.socket.getOutputStream());
  233. printWriter.write("disconnect\n");
  234. printWriter.flush();
  235. printWriter.write(mySocket.id+"\n");
  236. printWriter.flush();
  237. } catch (IOException e) {
  238. e.printStackTrace();
  239. }
  240. }
  241. }

 

  1. static class mySocket {
  2. public String id;
  3. public Socket socket;
  4. mySocket() {
  5. this.id = UUID.randomUUID().toString();
  6. try {
  7. this.socket = new Socket("192.168.157.1", 6666);
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. }

 接口类

  1. import java.net.Socket;
  2. public interface SocketInterface {
  3. /**
  4. * 开启监听
  5. */
  6. void read(Socket socket);
  7. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/178551
推荐阅读
相关标签
  

闽ICP备14008679号