//客户端
public class Client {
public static void main(String[] args) throws Exception {
System.out.println("====客户端===");
// 1.客户端要请求于服务端的管道连接
Socket socket=new Socket("127.0.0.1",9999);
// 2. 从socket通信管道中得到一个字节输出流
OutputStream outputStream = socket.getOutputStream();
// 3. 把低级的字节输出流包装成高级的打印流
PrintStream printStream = new PrintStream(outputStream);
// 4. 开始发消息出去
while(true){
Scanner scanner=new Scanner(System.in);
System.out.println("请说:");
printStream.println(scanner.nextLine());
printStream.flush();
}
}
}
//服务端
public class Server {
public static void main(String[] args) throws Exception {
System.out.println("===服务端启动==");
// 1. 注册端口
ServerSocket serverSocket=new ServerSocket(9999);
// 2. 定义一个循环不断接收客户端的连接请求
while(true){
// 3. 开始等待客户端的socket管道连接
Socket socket=serverSocket.accept();
//启动线程
new serverThread(socket).start();
}
}
}
//线程类
class serverThread extends Thread{
private Socket socket;
public serverThread(Socket socket){
this.socket=socket;
}
@Override
public void run(){
InputStream inputStream= null;
try {
// 4. 从socket管道中得到一个字节输入流
inputStream = socket.getInputStream();
// 5. 把直接输入流转换成字符输入流
Reader isr=new InputStreamReader(inputStream);
// 6. 把字符输入流包装缓冲字符输入流
BufferedReader br=new BufferedReader(isr);
// 7. 按照行读取信息,客户端也必须按照行来传输
String line;
while((line=br.readLine())!=null){
System.out.println(socket.getRemoteSocketAddress()+"说:"+line);
}
} catch (Exception e) {
System.out.println(socket.getRemoteSocketAddress()+"下线了");
}
}
}
|