//服务端作为中间端负责转发信息
//服务端
import java.net.*;
import java.util.*;
public class MyServer {
public static void main(String[] args) throws Exception {
List<Socket> list = new ArrayList<Socket>();
ServerSocket serv = new ServerSocket(6789);
Socket soc = null;
while (true) {
soc = serv.accept();
list.add(soc);
new Thread(new ServerThread(soc, list)).start();
}
}
}
//服务端接收和发送线程
import java.io.*;
import java.net.*;
import java.util.List;
public class ServerThread implements Runnable {
private Socket soc = null;
private List<Socket> list = null;
public ServerThread(Socket soc, List<Socket> list) {
this.soc = soc;
this.list = list;
}
public void run() {
while (true) {
try {
String str = server(soc);
for (Socket client : list) {
if (client != soc) {
send(str, client);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 服务端发送给客户端
public void send(String str, Socket client) throws Exception {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
out.write(str);
out.newLine();
out.flush();
}
// 服务端接收
public String server(Socket client) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("服务端收到" + str);
return str;
}
}
//客户端
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) throws Exception {
Socket client = new Socket(InetAddress.getLocalHost(), 6789);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
new Thread(new ClientThread(client)).start();
String str = null;
while ((str = in.readLine()) != null) {
if (str.equals("886")) {
break;
}
out.write(str);
out.newLine();
out.flush();
}
in.close();
out.close();
client.close();
}
}
//客户端接收服务端信息线程
public class ClientThread implements Runnable {
Socket client = null;
public ClientThread(Socket client){
this.client = client;
}
public void run() {
try {
BufferedReader clientin = new BufferedReader(new InputStreamReader(client.getInputStream()));
while(true){
System.out.println(clientin.readLine());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//关闭流通用工具
import java.io.*;
public class CloseUtil {
public static void close(Closeable... objs){
for (Closeable obj : objs) {
if(obj!=null){
try {
obj.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}