public class Client implements Serializable {
private Socket socket;// 套接字
public Client(){// 实例化构造
try {
socket = new Socket("localhost",8080);// TCP}catch(IOException e){
System.out.println("连接中断");
e.printStackTrace();}}
public voidstart(){
try {
OutputStream outputStream = socket.getOutputStream();// 使用输入流
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);// 启用行刷新
PrintWriter printWriter = new PrintWriter(bufferedWriter,true);// 使用流
Scanner scanner = new Scanner(System.in);
System.out.println("请输入:exit为退出");while(true){
String s = scanner.nextLine();if("exit".equals(s)){
printWriter.close();
bufferedWriter.close();
outputStreamWriter.close();
outputStream.close();break;}
printWriter.println(s);}}catch(IOException e){
System.out.println("信息中断");
e.printStackTrace();}}
public staticvoidmain(String[] args){
Client client = new Client();
client.start();}}
Server类
public class Server implements Serializable {
private ServerSocket serverSocket;
public Server(){
try {
serverSocket = new ServerSocket(8080);}catch(IOException e){
e.printStackTrace();}}
public voidstart(){
Socket accept = null;
try {
accept = serverSocket.accept();
InputStream inputStream = accept.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);while(true){
String s = bufferedReader.readLine();
System.out.println("接收"+s);}}catch(IOException e){
e.printStackTrace();
System.out.println("连接中断");}}
public staticvoidmain(String[] args){
Server server = new Server();
server.start();}}