socket is closed 谁帮我看看是哪里出了问题啊

lxl888888888 2016-07-02 02:50:10
package com.zxict.wisdomclass.util;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
public class ClassTeachServer extends Thread{
static ServerSocket serverSocket;
boolean isStarted = false;// 标志是否启动

List <Socket> clients = new ArrayList<Socket>();
public static void main(String[] args) {
new ClassTeachServer().start();
}
public void closeServerSocket(){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
try {
serverSocket = new ServerSocket(8060);// 在固定的端口上进行监听
isStarted = true;
} catch (IOException e) {
e.printStackTrace();
}
try {
clients.clear();
while (isStarted) {
Socket s = serverSocket.accept();// 接受连接请求
clients.add(s);// 加入客户端集合,以便将消息群发给每一个客户端
SocketAddress remoteSocketAddress = s.getRemoteSocketAddress();
System.out.println(remoteSocketAddress.toString());
System.out.println("a client connected!");
Client c = new Client(s,clients);// 启动一个线程

new Thread(c).start();

System.out.println(clients.size());
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
if (serverSocket != null)
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Client implements Runnable {
Socket socket;
private boolean connected = false;
private DataInputStream dataInputStream;
private DataOutputStream dataOutputStream;
List<Socket> clients;
public Client(Socket s,List<Socket> clients) {
this.socket = s;
this.clients=clients;
try {
dataInputStream = new DataInputStream(socket.getInputStream());
connected = socket.isConnected();
System.out.println("connected = " + connected);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
String content = null;
try {
content = dataInputStream.readUTF();
System.out.println(content);
while (content!=null) {
try {
DataOutputStream dos = null;
System.out.println("clients.size()=>" + clients.size());
for (int i = 0; i < clients.size(); i++) {
System.out.println(clients.get(i));
Socket client = clients.get(i);
if (client.isConnected()) {
dos = new DataOutputStream(client.getOutputStream());
}
if(!content.trim().equals("ok")){
dos.writeUTF(content);
}
}
dos.close();
} catch (EOFException e) {
}
sleep(3000);
}
} catch (Exception e) {
//clients.clear();
System.out.println(e.getMessage());
} finally {
try {
if (dataInputStream != null)
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}
}
...全文
258 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧