在上一篇博客中,我们实现了一个可以进行单次通信的聊天室。现在,我们可以将它升级,利用多线程进行多次聊天。
package Test02;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
Socket client=new Socket(InetAddress.getLocalHost(), 9986);
while(true) {
new Thread(new Send()).start();
new Thread(new Receive()).start();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package Test02;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
public class Receive implements Runnable{
private DataInputStream dis;
private boolean isrunning=true;
public Receive(Socket client) {
super();
try {
dis=new DataInputStream(client.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
isrunning=false;
}
}
public Receive() {
super();
}
public String receive() {
String string="";
try {
string=dis.readUTF();
} catch (IOException e) {
// TODO Auto-generated catch block
isrunning=false;
CloseUtil.Closeall(dis);
}
return string;
}
@Override
public void run() {
// TODO Auto-generated method stub
if(isrunning) {
System.out.println();
}
}
}
package Test02;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Send implements Runnable{
private DataOutputStream dos;
private boolean isrunning=true;
private BufferedReader console;
public Send(Socket client) {
try {
dos=new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
CloseUtil.Closeall(dos);
}
}
public Send() {
super();
console=new BufferedReader(new InputStreamReader(System.in));
}
public void send(String string) {
try {
dos.writeUTF(string);
} catch (IOException e) {
// TODO Auto-generated catch block
CloseUtil.Closeall(dos);
}
}
public String getInfo() {
String info="";
try {
info=console.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
CloseUtil.Closeall(dos);
}
return info;
}
@Override
public void run() {
if (isrunning) {
send(getInfo());
}
}
}
补充一下。关闭工具的写法;
package Test02;
import java.io.Closeable;
import java.io.IOException;
public class CloseUtil {
public static void Closeall(Closeable...io) {
for(Closeable temp:io) {
if(null!=temp) {
try {
temp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
这样利用这个工具就可以对多个或者不定个的流进行的关闭。
其中这只是对客户端进行的改造,同理服务器端也应该这样进行改造。
这样基本上一个多线程的聊天室就完成了。然后还有一些功能需要进行完善。
而且,我们发现服务器端的发送相当于自己发送自己接受,而不是发送给别人。