服务器端:
package TOP14.JT02.Music.Server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import TOP14.JT02.Music.To.User;
import TOP14.JT02.XZXM.To.Data;
public class ServerTxt {
static int count = 0;
public static HashMap<String,User> user = new HashMap<String,User>();
public static void main(String[] args) {
ServerSocket ss = null;
User msg = null;
try {
ss = new ServerSocket(9527);
} catch (Exception e) {
e.printStackTrace();
}
ObjectOutputStream dout =null;
while (true) {
try {
System.out.println("服务器监听用户注册信息:");
Socket sc = ss.accept();
System.out.println("==============" + (++count)+ "===============");
System.out.println("Client IP:" + sc.getInetAddress()); //得到请求方地址,并打印
ObjectInputStream din = new ObjectInputStream(sc.getInputStream());
msg = (User) din.readObject();
String name = msg.getName();
String password = msg.getPassword();
System.out.println(name+password);
dout = new ObjectOutputStream(sc.getOutputStream());
// String[] strs = msg.split(",");
// System.out.println("用户注册账户:" + strs[0]);
// System.out.println("用户注册密码:"+ strs[1]);
// String name = strs[0];
// String password = strs[1];
//首先读取txt文件map集合
ObjectInputStream input = new ObjectInputStream(new FileInputStream("C://776688.txt"));
user = (HashMap<String, User>)input.readObject();
// user = read();
//将用户信息写入TXT文件
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("C://776688.txt",true));
//设置一个开关判断是否把新用户资料加入集合
boolean isor = true;
//在此判断接收到的键在集合中是否已经存在
Iterator<String> it = user.keySet().iterator();
//循环遍历判断是否有此键
while(it.hasNext()){
//// System.out.println(it.next());
if (name.equals(it.next())) {
isor = false;
}
}
if (isor) {
user.put(name, msg);
output.writeObject(user);
output.flush();
msg.setMsg("true");
dout.writeObject(msg);
dout.flush();
}else{
msg.setMsg("false");
dout.writeObject(msg);
output.writeObject(user);
output.flush();
dout.flush();
}
din.close();
dout.close();
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
------解决方案--------------------
java.net.SocketException: Socket is closed
说明你把ServerSocket给close()掉了,那么它就不能再接受连接了。
服务器端代码:
ss.close();
修改为:
sc.close();