?? server.java
字號(hào):
import java.net.*;
import java.io.*;
import java.util.*;
class Server {
boolean started = false;
ServerSocket ss = null;
List<ClientRun> list = new ArrayList<ClientRun>();
public static void main(String[] args) {
new Server().start();
}
public void start()
{
try
{
ss = new ServerSocket(8888);
started = true;
}
catch (BindException be)
{
System.out.println("端口使用中!");
}
catch (IOException e)
{
System.out.println("服務(wù)器連接失敗!");
}
try
{
while (started) {
Socket s = ss.accept();
ClientRun cr = new ClientRun(s); //主線程只負(fù)責(zé)接收信息,每個(gè)客戶端連接進(jìn)來(lái)都會(huì)開(kāi)始一個(gè)新線程
new Thread(cr).start(); //把連接進(jìn)來(lái)的Socket傳到線程中。
list.add(cr);
System.out.println("系統(tǒng)提示:"+s.getInetAddress()+"已經(jīng)聯(lián)入");
}
}
catch (IOException e)
{
System.out.println("Client closed!");
}
}
/***********************************多線程實(shí)現(xiàn)多客戶端同時(shí)連接**************************************************/
class ClientRun implements Runnable
{
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
boolean bConnect = false;
public ClientRun(Socket s)
{
this.s = s;
try
{
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnect = true;
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void send(String str)
{
try
{
dos.writeUTF(str);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
while (bConnect)
{
String str = dis.readUTF();
System.out.println(str);
for (int i=0 ;i<list.size() ;i++ )
{
ClientRun cr = list.get(i);
cr.send(str);
}
}
}
catch (Exception e)
{
System.out.println(s.getInetAddress()+"離開(kāi)了!");
}
finally
{
try
{
if (dis != null) dis.close();
if (dos != null) dos.close();
if (s != null){
s.close();
s = null;
}
}
catch (IOException io)
{
io.printStackTrace();
}
}
}
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -