java網絡編程(TCP)-服務端
/**
* 此代碼是可以多客戶端連接的
* 服務器一定要先讀後寫,不能顛倒
* 不到萬不得已不要對ServerSocket進行關閉
*/
public class Server0 {
private static List<Socket> sockets = new ArrayList<Socket>();
public static void main(String[] args) {
ServerSocket ss = null;
try {
ss = new ServerSocket(10000);
while (true) {
sockets.add(s);
Server0 server0 = new Server0();
server0.new Start(s).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
class Start extends Thread {
Socket s = null; //k=客戶端
BufferedReader br = null;
public Start(Socket s) {
this.s = s;
}
public void run() {
try {
is = s.getInputStream();
br = new BufferedReader(new InputStreamReader(is,"GBK"));
while (true) {
System.out.println("客戶端輸入的內容:" + clientStr);
//輸入q時退出程序
if (clientStr.trim().equalsIgnoreCase("q")) {
break;
}
String outputStr = "你說:" + clientStr;
//向所有的客戶端發送輸入的消息
for (Socket s : sockets) {
OutputStream os = s.getOutputStream();
PrintStream ps = new PrintStream(os,true,"GBK");
ps.println(outputStr);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
java網絡編程(TCP)-服務端