1.关闭流的工具类
package 网络编程_手写聊天室_基础简易封装版;
public class CloseUtlis {
public void close(Closeable ... targets) {
for(Closeable target:targets ) {
if(target!=null) {
try {
target.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2.客户端接收类
package 网络编程_手写聊天室_基础简易封装版;
public class Receive implements Runnable{
private Socket client;
private boolean isRunning;
private DataInputStream in;
public Receive(Socket client) {
this.client=client;
try {
in=new DataInputStream(client.getInputStream());
} catch (IOException e) {
System.out.println("接收时出错!");
release();
}
}
@Override
public void run() {
isRunning =true;
while(isRunning) {
String str="";
try {
str = in.readUTF();
} catch (IOException e) {
System.out.println("读取时出错");
}
if(str!=null) {
System.out.println(str);
}
}
this.release();
}
public void release() {
CloseUtlis utlis =new CloseUtlis();
utlis.close(in);
isRunning=false;
}
}
3.客户端发送类
package 网络编程_手写聊天室_基础简易封装版;
public class Sent implements Runnable{
private Socket client;
private BufferedReader console;
private DataOutputStream out;
private boolean isRunning;
public Sent(Socket client) {
this.client=client;
console=new BufferedReader(new InputStreamReader(System.in));
try {
out =new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
System.out.println("发送数据时出错");
}
}
@Override
public void run() {
isRunning =true;
while(isRunning) {
String str="";
try {
str = console.readLine();
} catch (IOException e) {
System.out.println("读取时出错");
release();
}
try {
if(str!=null)
out.writeUTF(str);
out.flush();
} catch (IOException e) {
System.out.println("输出时出错");
release();
}
}
release();
}
public void release() {
CloseUtlis utlis =new CloseUtlis();
utlis.close(console,out);
isRunning=false;
}
}
4.客户端
package 网络编程_手写聊天室_基础简易封装版;
ublic class MultiClient {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket client = new Socket("localhost",8888);
new Thread(new Sent(client)).start();
new Thread(new Receive(client)).start();
}
}
服务器
package 网络编程_手写聊天室_基础简易封装版;
public class MultiServer {
public static void main(String[] args) throws IOException {
System.out.println("服务器开始工作");
ServerSocket server=new ServerSocket(8888);
boolean isRunning =true;
while(isRunning) {
Socket client = server.accept();
new Thread(new channel(client)).start();
}
}
static class channel implements Runnable{
private Socket client;
private DataInputStream in;
private int port;
private String buf;
channel(Socket client){
this.client=client;
}
@Override
public void run() {
try {
System.out.println("建立了一个连接");
while(true) {
enter();
sent();
}
} catch (IOException e) {
System.out.println("多线程中出错");
}
}
public void enter() throws IOException {
in =new DataInputStream(client.getInputStream());
buf=in.readUTF();
}
public void sent() throws IOException {
DataOutputStream out =new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
out.writeUTF(buf);
out.flush();
}
}
}