package com.test;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
//服务器端
public class Server {
public static void main(String[] args) throws IOException {
//创建服务器
ServerSocket ss = new ServerSocket(8080);
System.out.println("服务器等待连接....");
Socket socket = ss.accept();//监听器,监听客户端连接,并同意客户端连接,并建立通讯管道,也就是获得通讯的socket
System.out.println("服务器被连接");
// 建立通信
//建立管道
//接收客户端发来的信息
//对于服务器来说,是输入流
InputStream in = socket.getInputStream();
BufferedReader re = new BufferedReader(new InputStreamReader(in));
String str = re.readLine();
System.out.println(str);
//建立管道
//服务端发送信息
对于服务器来说,是输出流
Scanner input = new Scanner(System.in);
System.out.print("服务端讲话:");
String str2 = input.next();
OutputStream os = socket.getOutputStream();
PrintWriter pr = new PrintWriter(os,true);
pr.println(str2);
//关流
re.close();
in.close();
os.close();
pr.close();
socket.close();
}
}
//客户端
package com.test;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
//连接服务器
Socket socket = new Socket("Localhost",8080);
//建立管道
//客户端发送消息
//对于客户端来说,是输出流
System.out.print("客户端讲话:");
Scanner input = new Scanner(System.in);
String str = input.next();
OutputStream os = socket.getOutputStream();//获得输出流,流就相当于一个管道
PrintWriter pr = new PrintWriter(os,true);//包装成PrintWriter类
pr.println(str);
//建立管道
//客户端接收消息
//对于客户端来说,是输入流
InputStream in = socket.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
String str2 = bf.readLine();
System.out.println(str2);
in.close();
bf.close();
pr.close();
os.close();
socket.close();
}
}