TCP协议代码优化
package com.heima.tcp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Demo02_Client {
/**
* * 1.客户端
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("127.0.0.1", 12345);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //将字节流包装成了字符流
PrintStream ps = new PrintStream(socket.getOutputStream()); //PrintStream中有写出换行的方法
System.out.println(br.readLine());
ps.println("我想报名黑马程序员");
System.out.println(br.readLine());
ps.println("大哭!!!能不能给次机会");
socket.close();
}
}
===================================================
package com.heima.tcp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Demo02_Server {
/**
* * 2.服务端
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(12345);
Socket socket = server.accept(); //接受客户端的请求
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //将字节流包装成了字符流
PrintStream ps = new PrintStream(socket.getOutputStream()); //PrintStream中有写出换行的方法
ps.println("欢迎咨询黑马程序员");
//readLine()是以\r\n来结尾的
System.out.println(br.readLine());
ps.println("不好意思,爆满了");
System.out.println(br.readLine());
socket.close();
}
}