标签:思路 for 技术 port sock sleep inf style cat
代码链接:https://gitee.com/xiaoshishuya/codes
使用套接写连接编写一个简单的聊天室程序,客户端主函数放在Client_Main.java文件中,服务器端主函数放在Server_Main.java文件中
要求:
import java.io.*; import java.net.*; import java.util.*; public class Client_Main { public static void main (String args[]) { Socket mysocket; DataInputStream in=null; DataOutputStream out=null; try { mysocket = new Socket("127.0.0.1",2010); in = new DataInputStream(mysocket.getInputStream()); out = new DataOutputStream(mysocket.getOutputStream()); for (int i=0;i<10;i++) { Scanner scanner = new Scanner(System.in); String source = scanner.nextLine(); out.writeUTF(source); String s= in.readUTF(); System.out.println("客户收到服务器的回答:"+s); Thread.sleep(500); } } catch(Exception e) { System.out.println("服务器已断开"+e); } } }
Server_Main.java
import java.util.*; import java.io.*; import java.net.*; public class Server_Main { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); ServerSocket server = null; ServerThread thread; Socket kehu = null; while (true){ try { server = new ServerSocket(2010); } catch(IOException e1){ System.out.println("正在监听"); } try { System.out.println("等待客户呼叫"); kehu = server.accept(); System.out.println("客户地址:"+kehu.getInetAddress()); } catch (Exception e) { System.out.println("正在等待客户"+e); } if (kehu !=null){ new ServerThread(kehu).start(); } } } } class ServerThread extends Thread{ Scanner scanner = new Scanner(System.in); Socket socket; DataOutputStream out=null; DataInputStream in=null; String s = null; ServerThread(Socket t) { socket = t; try { out = new DataOutputStream(socket.getOutputStream()); in = new DataInputStream(socket.getInputStream()); for(int i=0;i<10;i++) { String s=in.readUTF(); System.out.println("服务器收到客户提问:"+s); out.writeUTF(scanner.nextLine()); } } catch (IOException e){} } }
其实做的有点蒙啊,特别是建表那个啊,没导明白呀,感觉自己真的是差的远呢,明明老师讲的很明白,听得也差不多,但一动手操作,我可能·是长了个假手,思路向一团乱麻,没个方向啊
代码行 | 博客字 | |
java | 90 | 316 |
标签:思路 for 技术 port sock sleep inf style cat
原文地址:https://www.cnblogs.com/xiaoshishuya/p/10113860.html