第四次过程性考核
码云:https://gitee.com/Maydayy/fourth_process_assessment/tree/master
使用套接写连接编写一个简单的聊天室程序,客户端主函数放在Client_Main.java文件中,服务器端主函数放在Server_Main.java文件中
要求:
- 1.客户端从控制台进行输入,并将客户端的输出内容和时间保存到“学号.txt”文件中
- 2.服务器端读取到客户端的程序后,给客户端以回应,并将客户端的输入内容与服务端的输出内容、时间保存到文本文件中
- 3.要求服务器端可以实现同时与多个客户端进行通信,与每一个客户端通信的内容,保存为一个“学号_ip.txt”的文件
- 4.4.提交文件结果包括:代码,通信后生成的txt文件
客户端:
1 import java.io.*; 2 import java.net.*; 3 import java.util.*; 4 public class Client_Main { 5 public static void main(String[] args) { 6 Scanner scanner=new Scanner(System.in); 7 Socket mysocket=null; 8 DataInputStream in=null; 9 DataOutputStream out=null; 10 Thread readData; 11 Read read=null; 12 try{ 13 mysocket=new Socket(); 14 read =new Read(); 15 readData=new Thread(read);//负责读取信息的线程 16 System.out.print("输入服务器的IP:"); 17 String IP=scanner.nextLine(); 18 System.out.print("输入端口号:"); 19 int port=scanner.nextLine(); 20 if (mysocket.isConnected()){} 21 else{ 22 InetAddress address=InetAddress.getByName("10.43.11.98"); 23 InetSocketAddress socketAddress=new InetSocketAddress(address,port); 24 mysocket.connect(socketAddress); 25 in =new DataInputStream(mysocket.getInputStream()); 26 out =new DataOutputStream(mysocket.getOutputStream()); 27 read.setDataInputStream(in); 28 readData.start();//启动负者读取信息的线程 29 } 30 } 31 catch(Exception e){ 32 System.out.println("服务器已断开"+e); 33 } 34 System.out.print("输入圆的半径(放弃请输入N):"); 35 while(scanner.hasNext()){ 36 double radius =0; 37 try{ 38 radius=scanner.nextDouble(); 39 } 40 catch (InputMismatchException exp){ 41 System.exit(0); 42 } 43 try { 44 out.writeDouble(radius); 45 } 46 catch(Exception e){} 47 } 48 } 49 }
服务器端:
1 import java.io.*; 2 import java.net.*; 3 import java.util.*; 4 public class Server_Main { 5 public static void main(String[] args) { 6 ServerSocket server =null; 7 ServerThread thread; 8 Socket you = null; 9 while(true) { 10 try{ server= new ServerSocket (2010); 11 } 12 catch (IOException e1){ 13 System.out.println("正在监听"); //ServerSocket 对象不能重复创建 14 } 15 try{ System.out.println("等待客户呼叫"); 16 you=server.accept () ; 17 System。out.println("'客户地址:"+you.getInetAddress()); 18 } 19 catch (IOException e) { 20 System.out .println("正在等待客户"); 21 } 22 if(you!=null) { 23 new ServerThread (you).start()); //为每一客户启动一个专门的线程 24 } 25 } 26 } 27 } 28 29 class ServerThread extends Thread { 30 Socket socket; 31 DataOutputStream out = null; 32 DataInputStream in = null; 33 String s = null; 34 ServerThread(Socket t) { 35 socket =t; 36 try { out = new DataOutputStream (socket.getOutputStream()); 37 in =new DataInputStream (socket.getInputstream()); 38 } 39 catch(IOException e){} 40 } 41 public void run(){ 42 while(true){ 43 try { 44 double r =in.readDouble(); 45 double area=Math.PI*r*r; 46 out.writeDouble(area); 47 } 48 catch (IOException e){ 49 System.out.println("客户离开"); 50 return; 51 } 52 53 } 54 } 55 }
考试总结:这学期学的没有那么扎实,这次考试是这学期的回顾