1.使用Socket进行编写代码:这里还涉及多线程的简单应用。
2.首先创建一个MyWriter类,用于发送客户端和服务器端的聊天信息。
/** Copyright (c) 2020, 2023, All rights reserved.**/import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;/*** <p>Project: JavaStudy - MyWrter</p>* <p>Powered by scl On 2023-07-26 12:43:49</p>* <p>描述:<p>** @author scl [1846080280@qq.com]* @version 1.0* @since 17*/
public class MyWriter implements Runnable {private String msg;private PrintWriter out;private Socket c;public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public PrintWriter getOut() {return out;}public void setOut(PrintWriter out) {this.out = out;}public Socket getC() {return c;}public void setC(Socket c) {this.c = c;}public MyWriter(String msg, Socket c) {this.msg = msg;try {this.out = new PrintWriter(c.getOutputStream());} catch (Exception e) {e.printStackTrace();}this.c = c;}public MyWriter() {}@Overridepublic void run() {while (true) {Scanner sc = new Scanner(System.in);out.printf("%s %s",this.msg ,sc.nextLine() + "\r\n");out.flush();}}
}
3.再创建一个MyReader类,用于接收客户端和服务器端的聊天信息。
/** Copyright (c) 2020, 2023, All rights reserved.**/import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;/*** <p>Project: JavaStudy - MyReader</p>* <p>Powered by scl On 2023-07-26 12:51:16</p>* <p>描述:<p>** @author scl [1846080280@qq.com]* @version 1.0* @since 17*/
public class MyReader implements Runnable {private Socket c;private BufferedReader br;public MyReader(Socket c) {this.c = c;try {this.br = new BufferedReader(new InputStreamReader(c.getInputStream()));} catch (Exception e) {e.printStackTrace();}}public Socket getC() {return c;}public void setC(Socket c) {this.c = c;}public BufferedReader getBr() {return br;}public void setBr(BufferedReader br) {this.br = br;}public MyReader() {}@Overridepublic void run() {while (true) {try {System.out.println(this.br.readLine());} catch (Exception e) {e.printStackTrace();}}}
}
4.然后就是调用着两个线程,创建一个服务器端,来接收和发送信息。
/** Copyright (c) 2020, 2023, All rights reserved.**/import java.net.ServerSocket;
import java.net.Socket;/*** <p>Project: JavaStudy - MyServer</p>* <p>Powered by scl On 2023-07-26 12:55:15</p>* <p>描述:<p>** @author scl [1846080280@qq.com]* @version 1.0* @since 17*/
public class MyServer {public static void main(String[] args) {try {ServerSocket s=new ServerSocket(9090);Socket c=s.accept();new Thread( new MyWriter("服务器:",c)).start();new Thread(new MyReader(c)).start();} catch (Exception e) {e.printStackTrace();}}
}
5.创建一个客户端来发送和接信息。
/** Copyright (c) 2020, 2023, All rights reserved.**/import java.net.Socket;/*** <p>Project: JavaStudy - Myclinet</p>* <p>Powered by scl On 2023-07-26 12:58:52</p>* <p>描述:<p>** @author scl [1846080280@qq.com]* @version 1.0* @since 17*/
public class Myclinet {public static void main(String[] args) {try {Socket c=new Socket("192.168.21.30",9090);new Thread(new MyReader(c)).start();new Thread(new MyWriter("客户:",c)).start();} catch (Exception e) {e.printStackTrace();}}
}