当前位置:   article > 正文

Java网络编程-服务端程序实现_java网络编程 服务端怎么整

java网络编程 服务端怎么整

   打算在微信公众号记录比较好,csdn不定时记录,有兴趣可以逛逛

                                                           

 

    最近学习了Java的net包,看了网上的开源代码,整理了一部分服务端代码,实现了消息监听,直接上代码。

一。新建了一个消息类,用于存储消息进行传输

  1. package com.xing.studyTest.net.im.model;
  2. import java.io.Serializable;
  3. import java.util.HashMap;
  4. import java.util.HashSet;
  5. /**
  6. * 消息信息
  7. * @author xinghua
  8. *
  9. */
  10. public class MessageBean implements Serializable{
  11. private static final long serialVersionUID = 1L;
  12. private int type; // 1私聊 0上下线更新 -1下线请求 2请求发送文件 3.确定接收文件
  13. private HashSet<String> clients; // 存放选中的客户
  14. private HashSet<String> to;//
  15. public HashMap<String, MessageBean> onlines;//
  16. private String info;//信息
  17. private String timer;//时间
  18. private String name;//昵称
  19. private String fileName;//文件名
  20. private int size;//文件大小
  21. private String ip;//IP
  22. private int port;//端口
  23. public int getSize() {
  24. return size;
  25. }
  26. public void setSize(int size) {
  27. this.size = size;
  28. }
  29. public String getFileName() {
  30. return fileName;
  31. }
  32. public void setFileName(String fileName) {
  33. this.fileName = fileName;
  34. }
  35. public HashSet<String> getTo() {
  36. return to;
  37. }
  38. public void setTo(HashSet<String> to) {
  39. this.to = to;
  40. }
  41. public int getType() {
  42. return type;
  43. }
  44. public void setType(int type) {
  45. this.type = type;
  46. }
  47. public HashSet<String> getClients() {
  48. return clients;
  49. }
  50. public void setClients(HashSet<String> clients) {
  51. this.clients = clients;
  52. }
  53. public String getInfo() {
  54. return info;
  55. }
  56. public void setInfo(String info) {
  57. this.info = info;
  58. }
  59. public String getTimer() {
  60. return timer;
  61. }
  62. public void setTimer(String timer) {
  63. this.timer = timer;
  64. }
  65. public String getName() {
  66. return name;
  67. }
  68. public void setName(String name) {
  69. this.name = name;
  70. }
  71. public String getIp() {
  72. return ip;
  73. }
  74. public void setIp(String ip) {
  75. this.ip = ip;
  76. }
  77. public int getPort() {
  78. return port;
  79. }
  80. public void setPort(int port) {
  81. this.port = port;
  82. }
  83. public HashMap<String, MessageBean> getOnlines() {
  84. return onlines;
  85. }
  86. public void setOnlines(HashMap<String, MessageBean> onlines) {
  87. this.onlines = onlines;
  88. }
  89. /* (non-Javadoc)
  90. * @see java.lang.Object#toString()
  91. */
  92. @Override
  93. public String toString() {
  94. return " [type=" + type + ", clients=" + clients + ", to=" + to + ", onlines=" + onlines + ", info="
  95. + info + ", timer=" + timer + ", name=" + name + ", fileName=" + fileName + ", size=" + size + ", ip="
  96. + ip + ", port=" + port + "]";
  97. }
  98. }

二、因为要存储在线用户和用户连接信息,所以还需要个实体类

  1. package com.xing.studyTest.net.im.model;
  2. import java.io.Serializable;
  3. import java.net.Socket;
  4. /**
  5. * 连接信息
  6. * @author xinghua
  7. *
  8. */
  9. public class SocketBean implements Serializable{
  10. private static final long serialVersionUID = 1L;
  11. private String name;//名称
  12. private Socket socket;//socket
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public Socket getSocket() {
  20. return socket;
  21. }
  22. public void setSocket(Socket socket) {
  23. this.socket = socket;
  24. }
  25. /* (non-Javadoc)
  26. * @see java.lang.Object#toString()
  27. */
  28. @Override
  29. public String toString() {
  30. return "ServerBean [name=" + name + ", socket=" + socket + "]";
  31. }
  32. }

 

三,好了,接下来就是Server代码

  1. package com.xing.studyTest.net.im.server;
  2. import java.io.IOException;
  3. import java.io.ObjectInputStream;
  4. import java.io.ObjectOutputStream;
  5. import java.net.ServerSocket;
  6. import java.net.Socket;
  7. import java.util.Collection;
  8. import java.util.HashMap;
  9. import java.util.HashSet;
  10. import java.util.Iterator;
  11. import java.util.Set;
  12. import java.util.concurrent.Executor;
  13. import java.util.concurrent.Executors;
  14. import com.xing.studyTest.net.im.model.MessageBean;
  15. import com.xing.studyTest.net.im.model.SocketBean;
  16. /**
  17. *
  18. * @author xinghua
  19. *
  20. */
  21. public class SocketServer {
  22. private static ServerSocket ss;//服务端服务对象
  23. public static HashMap<String, SocketBean> onlines;//存储上线的Socket信息
  24. //1.准备服务端对象及容器
  25. static {
  26. try {
  27. ss = new ServerSocket(8520);
  28. onlines = new HashMap<String, SocketBean>();//新建一个容器存放客户端连接信息
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. //2.多线程实现监听消息处理
  34. class CatClientThread extends Thread {
  35. private Socket socket;//链接
  36. private MessageBean messageBean;//消息
  37. private ObjectInputStream ois;//读取消息
  38. private ObjectOutputStream oos;//输出消息
  39. public CatClientThread(Socket socket) {
  40. this.socket = socket;
  41. }
  42. @Override
  43. public void run() {
  44. try {
  45. messageBean = (MessageBean)new ObjectInputStream(socket.getInputStream()).readObject();
  46. System.out.println("获取消息对象:"+messageBean);
  47. //根据请求类型进行不同的操作
  48. switch (messageBean.getType()) {
  49. case 0: { // 上线
  50. System.out.println("上线1.记录上线客户的用户名和端口,组装用户名和Socket连接,添加到容器中");
  51. SocketBean socketBean = new SocketBean();
  52. socketBean.setName(messageBean.getName());
  53. socketBean.setSocket(socket);
  54. onlines.put(messageBean.getName(), socketBean);//添加到onlines中
  55. System.out.println("上线2.已存储上线,开始准备发送消息给客户端");
  56. System.out.println("当前在线人数:【"+onlines.keySet().size()+"】个");
  57. MessageBean returnMessageBean = new MessageBean();
  58. returnMessageBean.setType(0);
  59. returnMessageBean.setInfo(messageBean.getTimer() + " [ " + messageBean.getName() + " ]上线了");
  60. System.out.println("上线3.发送消息准备完毕,发送给全部用户:");
  61. System.out.println(onlines.keySet());
  62. // System.out.println(onlines.values());
  63. HashSet<String> set = new HashSet<String>();
  64. set.addAll(onlines.keySet());
  65. returnMessageBean.setClients(set);
  66. sendAll(returnMessageBean);
  67. System.out.println("上线4.发送有人上线消息给全部用户完毕");
  68. break;
  69. }
  70. case -1: { // 下线
  71. // try {
  72. // oos = new ObjectOutputStream(socket.getOutputStream());
  73. // oos.writeObject(messageBean);
  74. // oos.flush();
  75. // } catch (IOException e) {
  76. // e.printStackTrace();
  77. // }
  78. System.out.println("下线1.将用户从容器删除");
  79. onlines.remove(messageBean.getName());
  80. System.out.println("下线2.用户已移除,准备发送消息告诉所有人他下线了");
  81. MessageBean returnMessageBean = new MessageBean();
  82. returnMessageBean.setType(-1);
  83. returnMessageBean.setInfo(messageBean.getTimer() + " [ " + messageBean.getName() + " ]下线了");
  84. System.out.println("下线3.发送消息准备完毕,发送给全部用户");
  85. sendAll(returnMessageBean);
  86. System.out.println("下线4.发送有人下线消息给全部用户完毕");
  87. break;
  88. }
  89. case 1: { // 聊天
  90. System.out.println("聊天1.组装消息,准备给选中的用户发送");
  91. MessageBean returnMessageBean = new MessageBean();
  92. returnMessageBean.setType(1);
  93. returnMessageBean.setClients(messageBean.getClients());
  94. returnMessageBean.setName(messageBean.getName());//选中的用户昵称
  95. returnMessageBean.setInfo(messageBean.getInfo());//消息内容
  96. returnMessageBean.setTimer(messageBean.getTimer());//发送时间
  97. System.out.println("聊天2.组装消息准备完毕开始发送");
  98. System.out.println(returnMessageBean);
  99. sendMessage(returnMessageBean);
  100. System.out.println("聊天3.发送消息完毕");
  101. break;
  102. }
  103. case 2: { // 请求接受文件
  104. break;
  105. }
  106. case 3: { // 确定接收文件
  107. break;
  108. }
  109. default: {
  110. break;
  111. }
  112. }
  113. } catch (Exception e) {
  114. e.printStackTrace();
  115. } finally {
  116. close();
  117. }
  118. }
  119. // 向选中的用户发送数据
  120. private void sendMessage(MessageBean messageBean) {
  121. // 首先取得所有的values
  122. Set<String> cbs = onlines.keySet();
  123. Iterator<String> it = cbs.iterator();
  124. // 选中客户
  125. HashSet<String> clients = messageBean.getClients();
  126. while (it.hasNext()) {
  127. // 在线客户
  128. String client = it.next();
  129. // 选中的客户中若是在线的,就发送
  130. if (clients.contains(client)) {
  131. Socket c = onlines.get(client).getSocket();
  132. ObjectOutputStream oos;
  133. try {
  134. oos = new ObjectOutputStream(c.getOutputStream());
  135. oos.writeObject(messageBean);
  136. oos.flush();
  137. } catch (IOException e) {
  138. e.printStackTrace();
  139. }
  140. }
  141. }
  142. }
  143. /*
  144. * 向所有的用户发送数据
  145. */
  146. public void sendAll(MessageBean serverBean) {
  147. Collection<SocketBean> clients = onlines.values();
  148. Iterator<SocketBean> it = clients.iterator();
  149. ObjectOutputStream oos;
  150. while (it.hasNext()) {
  151. Socket c = it.next().getSocket();
  152. try {
  153. oos = new ObjectOutputStream(c.getOutputStream());
  154. oos.writeObject(serverBean);
  155. oos.flush();
  156. } catch (IOException e) {
  157. e.printStackTrace();
  158. }
  159. }
  160. }
  161. /*
  162. * 关闭Socket连接
  163. */
  164. private void close() {
  165. if (oos != null) {
  166. try {
  167. oos.close();
  168. } catch (IOException e) {
  169. e.printStackTrace();
  170. }
  171. }
  172. if (ois != null) {
  173. try {
  174. ois.close();
  175. } catch (IOException e) {
  176. e.printStackTrace();
  177. }
  178. }
  179. if (socket != null) {
  180. try {
  181. socket.close();
  182. } catch (IOException e) {
  183. e.printStackTrace();
  184. }
  185. }
  186. }
  187. }
  188. /*
  189. * 循环调用监听与本Socket的连接信息,
  190. */
  191. public void start() {
  192. try {
  193. Executor executor = Executors.newFixedThreadPool(3);
  194. while (true) {
  195. String name = ss.getInetAddress().getHostName();
  196. System.out.println("启动服务器监听程序启动完成,快来给我发送消息把!:host:"+name+"port:"+ss.getLocalPort());
  197. Socket socket = ss.accept();
  198. name = socket.getInetAddress().getHostName();
  199. System.out.println("收到host:"+name+"port:"+socket.getPort()+"的消息处理开始");
  200. Long timeStart = System.currentTimeMillis();
  201. executor.execute(new CatClientThread(socket));
  202. // new CatClientThread(socket).start();
  203. System.out.println("收到host:"+name+"port:"+socket.getPort()+"的消息处理完毕,用时【"+(System.currentTimeMillis()-timeStart)+"】秒");
  204. }
  205. } catch (IOException e) {
  206. e.printStackTrace();
  207. }
  208. }
  209. }

 

四、最后启动:

  1. package com.xing.studyTest.net.im.main;
  2. import com.xing.studyTest.net.im.server.SocketServer;
  3. /**
  4. * 启动服务端
  5. * @author xinghua
  6. *
  7. */
  8. public class ServerApplication {
  9. public static void main(String[] args) {
  10. new SocketServer().start();
  11. }
  12. }

 

五、此时就在监听 等待客户端发消息来连接了

 

 

六、简单的客户端搞个上线信息发送:

  1. package com.xing.studyTest.net.im.main;
  2. import java.io.DataInputStream;
  3. import java.io.DataOutputStream;
  4. import java.io.IOException;
  5. import java.io.ObjectInputStream;
  6. import java.io.ObjectOutputStream;
  7. import java.net.Socket;
  8. import java.text.SimpleDateFormat;
  9. import java.util.Date;
  10. import java.util.Scanner;
  11. import com.xing.studyTest.net.im.model.MessageBean;
  12. /**
  13. * 客户端
  14. * @author xinghua
  15. *
  16. */
  17. public class ClientApplication2 {
  18. private static final String HOST = "localhost";//host
  19. private static final int PORT = 8520;//端口
  20. private static final String NAME = "雅楠";//host
  21. public static void main(String[] args) {
  22. Socket socket = null;
  23. DataInputStream dataInputStream = null;
  24. DataOutputStream dataOutputStream = null;
  25. try {
  26. Scanner input = new Scanner(System.in);
  27. System.out.println("请输入一个昵称");
  28. String name = input.nextLine();
  29. System.out.println("你的昵称是【"+name+"】,开始连接。。。");
  30. //上线
  31. MessageBean messageBean = new MessageBean();
  32. messageBean.setType(0);
  33. messageBean.setName(name);
  34. messageBean.setTimer(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
  35. socket = new Socket(HOST, PORT);
  36. // System.out.println("发起请求到->"+HOST+":"+PORT);
  37. ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
  38. oos.writeObject(messageBean);
  39. oos.flush();
  40. System.out.println("获取响应数据");
  41. MessageBean resMB = (MessageBean)new ObjectInputStream(socket.getInputStream()).readObject();
  42. System.out.println(resMB);
  43. System.out.println();
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. } finally {
  47. try {
  48. if(dataInputStream != null){
  49. dataInputStream.close();
  50. }
  51. if(dataOutputStream != null){
  52. dataOutputStream.close();
  53. }
  54. if(socket != null){
  55. socket.close();
  56. }
  57. } catch (IOException e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. }
  62. }

 

这是搞了个上线消息发送,并收到响应,客户端应该是不停的监听服务端发送消息,以实现聊天,还没写出来,下次再贴出来吧

 

 

好吧,自己发给自己了,啊哈哈哈哈

 

 

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

闽ICP备14008679号