007socket基本使用

    技术2022-07-10  105

    package sock; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class MySock7 { public static void main(String[] args) throws Exception { Socket socket = new Socket("127.0.0.1", 32112 ); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true); String line = null; for (int i = 0; i < 3; i++) { String readLine = bufferedReader.readLine(); if (readLine == null) { break; } printWriter.println(readLine); String msg = bufferedReader1.readLine(); System.out.println(msg); if (msg.contains("欢迎")) { break; } } bufferedReader.close(); socket.close(); } } class MySerd7 { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(32112); while (true) { Socket accept = serverSocket.accept(); new Thread(new MySerThead(accept)).start(); } } } class MySerThead implements Runnable { Socket socket; public MySerThead(Socket socket) { this.socket = socket; } @Override public void run() { String ip = socket.getInetAddress().getHostAddress(); try { // System.out.println("ip = " + ip); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream() )); String name=null; PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true); String line =null; boolean flag = false; for (int i = 0; i < 3; i++) { BufferedReader bufferedReader1 = new BufferedReader(new FileReader("d:/in.txt")); name = bufferedReader.readLine();//证明是一个对象。 if (name == null) { break; } System.out.println("name = " + name); while ((line = bufferedReader1.readLine()) != null) { System.out.println("line = " + line); if (line.equals(name)) { System.out.println(name+"登陆成功"); printWriter.println(name+":欢迎你的到来!"); flag = true; break; } } if (!flag) { System.out.println(name+":尝试登陆"); printWriter.println(name+":用户名不存在"); } bufferedReader1.close(); } // if(!flag) // printWriter.println(name+":你搞砸了!"); socket.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(ip+":you lose"); } finally { } } }
    Processed: 0.019, SQL: 9