接收信息的线程
/*
* 接收信息的线程
* */
public class ReceiveMsgThread implements Runnable {
private Socket s;
private String name;
public ReceiveMsgThread(){
}
public ReceiveMsgThread(Socket socket,String name){
this.s=socket;
this.name =name;
}
@Override
public void run() {
try ( //打开输入对象,接收对方Socket发送过来的数据
InputStream is = s.getInputStream();
//封装字符输入流
BufferedReader br = new BufferedReader(new InputStreamReader(is));
) {
while (true){
String str = br.readLine();
System.out.println(str);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
要发送数据的Socket
/*
* 发送信息线程
* */
public class SendMagThread implements Runnable{
/*
* 要发送数据的Socket
* */
private Socket s;
public SendMagThread(){
}
public SendMagThread(Socket s){
this.s=s;
}
@Override
public void run() {
try( //获取输出流,向对方Socket发送消息
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os);
){
//获取键盘输入对象
Scanner scanner = new Scanner(System.in);
while(true){
//获取键盘输入的内容
String str = scanner.next();
//发送输入的内容
pw.println(str);
pw.flush();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
public class Client {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 5200);//创建并开启消息线程
new Thread(new SendMagThread(s) ).start();
//创建并开启接收消息线程
new Thread(new ReceiveMsgThread(s,"服务器") ).start();
}catch (Exception e){
e.printStackTrace();
}
}
}
public class Server {
public static void main(String[] args) {
try (ServerSocket ss = new ServerSocket(5200);
){
Socket s = ss.accept();
System.out.println("客户端连接成功");
new Thread(new SendMagThread(s)).start();
new Thread(new ReceiveMsgThread(s,"客户端")).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}