A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

服务端:
import java.net.Socket;
import java.net.ServerSocket;
import java.io.*;
public class SocketServer {
public static void main(String[] args){
   try{
   ServerSocket ss = null;
   ss = new ServerSocket(4700);
   Socket s = ss.accept();
   BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
   BufferedReader din = new BufferedReader(new InputStreamReader(System.in));
   PrintWriter out = new PrintWriter(s.getOutputStream());
   System.out.println("Client:"+in.readLine());
   String line = din.readLine();
   while(!line.equals("bye")){
   out.print(line);
   System.out.println("Server:"+line);
   System.out.println("Client:"+in.readLine());
   line = din.readLine();
   }
   in.close();
   out.close();
   ss.close();
   }catch(IOException e){
   System.out.println("文件读取错误");
   }
   }
}
客户端:
import java.net.Socket;
import java.io.*;
import java.net.ServerSocket;
public class MySocket {
   public static void main(String[] args)throws Exception{
   Socket s = new Socket("127.0.0.1",4700);
   try{
   BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
   BufferedReader din = new BufferedReader(new InputStreamReader(System.in));
   PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
     
  String st = din.readLine();
   while(!st.equals("bye")){
   out.println(st);
   out.flush();
   System.out.println("Client:"+st);
   System.out.println(in.readLine());
   st = din.readLine();
   }
   in.close();
   din.close();
   s.close();
   }catch(IOException e){
   return;
   }
   }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马