78 lines
2.3 KiB
Java
78 lines
2.3 KiB
Java
package 大作业;
|
|
|
|
import java.io.*;
|
|
import java.net.*;
|
|
|
|
class CilentSocketMultThread extends Thread{
|
|
private Socket socket;
|
|
private BufferedReader in;
|
|
public PrintWriter out;
|
|
private ChatingRoom chatingRoom;
|
|
|
|
public CilentSocketMultThread(InetAddress addr,ChatingRoom c)throws IOException{
|
|
chatingRoom=c;
|
|
try{
|
|
socket=new Socket(addr,Sever_Socket.PORT);
|
|
System.out.println("启动客户端:"+socket);
|
|
} catch(IOException exception){
|
|
System.out.println(exception);
|
|
System.out.println("创建客户端失败");
|
|
chatingRoom.chat_Frame.append("输入了无效的IP地址或该客户端未开启");
|
|
}
|
|
try {
|
|
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
|
|
out=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
|
|
out.println(chatingRoom.Name+"加入聊天室"+'\n');
|
|
start();
|
|
} catch (IOException e) {
|
|
System.out.println(e);
|
|
System.out.println("流异常");
|
|
try {
|
|
socket.close();
|
|
} catch (IOException exception) {
|
|
System.out.println(exception);
|
|
System.out.println("scoket关闭异常");
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
public void run(){
|
|
try {
|
|
while (true) {
|
|
String str=in.readLine();
|
|
chatingRoom.chat_Frame.append(str+'\n');
|
|
if(chatingRoom.isClose==true)
|
|
break;
|
|
}
|
|
} catch (IOException e) {
|
|
chatingRoom.chat_Frame.append("聊天室关闭");
|
|
System.out.println(e);
|
|
System.out.println("流异常");
|
|
try {
|
|
socket.close();
|
|
} catch (IOException e1) {
|
|
System.out.println(e1);
|
|
System.out.println("socket关闭异常");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public class Client_Scoket {
|
|
/*static final int MAX_THREAD=10;
|
|
|
|
public static void main(String[] args) throws IOException,InterruptedException {
|
|
InetAddress addr=InetAddress.getByName(null);
|
|
while(true){
|
|
if(CilentSocketMultThread.threadCount()<MAX_THREAD)
|
|
new CilentSocketMultThread(addr);
|
|
Thread.sleep(100);
|
|
}
|
|
}*/
|
|
|
|
}
|
|
|
|
|