package assignment2;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.Socket;
/**
* @DESCRIPATION
* @AUTHOR 戴超
* @DATE 2018/6/19
**/
public class Receiver implements Runnable {
BufferedReader br = null;
Socket socket = null;
public Receiver(BufferedReader br, Socket socket) {
this.br = br;
this.socket = socket;
}
@Override
public void run() {
while (socket.isConnected() && socket.isBound() && !socket.isClosed()) {
String msg = null;
try {
msg = br.readLine();
if (msg != null && msg.trim().length() > 0) {
if ("exit".equals(msg)) {
socket.close();
}
}
System.out.println("他说:" + msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package assignment2;
import sun.reflect.generics.scope.Scope;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
/**
* @DESCRIPATION
* @AUTHOR 戴超
* @DATE 2018/6/19
**/
public class Sender implements Runnable {
BufferedWriter bw = null;
Socket socket = null;
Scanner scan = new Scanner(System.in);
public Sender(BufferedWriter bw, Socket s) {
this.bw = bw;
socket = s;
}
@Override
public void run() {
while (socket.isConnected() && socket.isBound() && !socket.isClosed()) {
try {
String str = scan.next();
if ("exit".equals(str)) {
bw.write(str);
bw.close();
socket.close();
System.exit(0);
} else {
bw.write(str + "\n");
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package assignment2;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
/**
* @DESCRIPATION java 8 的优雅聊天
* @AUTHOR 戴超
* @DATE 2018/6/19
**/
public class Client {
public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1", 8888);
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
BufferedReader br = new BufferedReader(new InputStreamReader(is));
new Thread(new Receiver(br , s)).start();
new Thread(new Sender(bw, s)).start();
}
}
package assignment2;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
* @DESCRIPATION java 8 的优雅聊天
* @AUTHOR 戴超
* @DATE 2018/6/19
**/
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(8888);
System.out.println("启动服务器!");
ss.setSoTimeout(15 * 1000);
Socket s = ss.accept();
System.out.println("客户端:" + s.getInetAddress() + "已连接到服务器");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
new Thread(new Receiver(br, s)).start();
new Thread(new Sender(bw, s)).start();
}
}