![一个发送另一个接收,每次只能发1行内容](https://i-blog.csdnimg.cn/blog_migrate/3f2ea2d40e741bf1b15767946cd33cd7.png)
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(2345);
System.out.println("服务器已启动...");
Socket s = server.accept();
System.out.println("客户端连接:"+s.getInetAddress().getHostAddress());
MsgUtils.sendMsg(s.getOutputStream(),"来啦,老弟!!!");
Scanner sc = new Scanner(System.in);
while(true) {
String msg = MsgUtils.readLine(s.getInputStream());
System.out.println("client:"+msg);
msg = sc.nextLine();
MsgUtils.sendMsg(s.getOutputStream(), msg);
}
}
}
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("192.168.7.141",2345);
Scanner sc = new Scanner(System.in);
while(true) {
String msg = MsgUtils.readLine(s.getInputStream());
System.out.println("server:"+msg);
msg = sc.nextLine();
MsgUtils.sendMsg(s.getOutputStream(), msg);
}
}
}
public class MsgUtils {
public static String readLine(InputStream is) throws IOException {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String msg = br.readLine();
return msg;
}
public static void sendMsg(OutputStream os,String msg) {
PrintWriter pw = new PrintWriter(os);
pw.println(msg);
pw.flush();
}
}