客户端:
public class ThreadClient {
public static void main(String[] args) {
Socket socket = null;
PrintWriter pw = null;
try {
// 连接远程服务器
socket = new Socket("127.0.0.1", 8081);
System.out.println("可以聊天了:");
pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
new MyRecive(socket).start();
// 主线程发消息
Scanner scanner = new Scanner(System.in);
String line = null;
while ((line = scanner.nextLine()) != null) {
pw.println(line);
pw.flush();
if (line.equals("bye")) {
System.exit(0);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
pw.close();
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class MyRecive extends Thread {
Socket socket;
BufferedReader br = null;
public MyRecive(Socket socket) {
this.socket = socket;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
String line = null;
try {
while ((line = br.readLine()) != null) {
System.out.println("服务端: "+line);
}
} catch (IOException e1) {
e1.printStackTrace();
}finally{
try {
br.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务端:
public class ThreadServer {
public static void main(String[] args) throws IOException {
// 服务器的套接字:监听客户的连接 tcp
ServerSocket serverSocket = new ServerSocket(8081);
Socket socket = null;
while (true) {
// 获得连接请求--阻塞的
socket = serverSocket.accept();
// 启动线程
new SThread(socket).start();
}
}
}
class SThread extends Thread {
BufferedReader br = null;
PrintWriter pw = null;
private Socket socket;
public SThread(Socket socket) {
this.socket = socket;
try {
// 获取输出流
pw = new PrintWriter(new OutputStreamWriter(
socket.getOutputStream()));
// 将获得输入流转换成字节型,然后转换成buffer型缓冲
br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
Scanner sn = new Scanner(System.in);
String line = "";
// 读取数据
while ((line = br.readLine()) != null) {
System.out.println("来自客户端【"
+ socket.getInetAddress().getHostAddress() + "】说:"
+ line);
System.out.print("请输入:");
String nextLine = sn.nextLine();
pw.println(nextLine);
pw.flush();
if (nextLine.equals("bye")) {
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}