第三步 實(shí)現(xiàn)信息共享:在Socket上的實(shí)時(shí)交流
網(wǎng)絡(luò)的偉大之一也是信息共享,Server可以主動(dòng)向所有Client廣播消息,同時(shí)Client也可以向其它Client發(fā)布消息。下面看看如何開(kāi)發(fā)一個(gè)可以實(shí)時(shí)傳遞消息的程序。
設(shè)計(jì)原理:
服務(wù)器端接受客戶(hù)端的連接請(qǐng)求,同時(shí)啟動(dòng)一個(gè)線程處理這個(gè)連接,線程不停的讀取客戶(hù)端輸入,然后把輸入加入隊(duì)列中,等候處理。在線程啟動(dòng)的同時(shí)將線程加入隊(duì)列中,以便在需要的時(shí)候定位和取出。
{源碼}
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;
public class Server extends ServerSocket
{
private static ArrayList User_List = new ArrayList();
private static ArrayList Threader = new ArrayList();
private static LinkedList Message_Array = new LinkedList();
private static int Thread_Counter = 0;
private static boolean isClear = true;
protected static final int SERVER_PORT = 10000;
protected FileOutputStream LOG_FILE = new FileOutputStream("d:/connect.log", true);
public Server() throws FileNotFoundException, IOException
{
super(SERVER_PORT);
new Broadcast();
//append connection log
Calendar now = Calendar.getInstance();
String str = "[" + now.getTime().toString() + "] Accepted a connection\015\012";
byte[] tmp = str.getBytes();
LOG_FILE.write(tmp);
try
{
while (true)
{
Socket socket = accept();
new CreateServerThread(socket);
}
}
finally
{
close();
}
}
public static void main(String[] args) throws IOException
{
new Server();
}
//--- Broadcast
class Broadcast extends Thread
{
public Broadcast()
{
start();
}
public void run()
{
while (true)
{
if (!isClear)
{
String tmp = (String)Message_Array.getFirst();
for (int i = 0; i < Threader.size(); i++)
{
CreateServerThread client = (CreateServerThread)Threader.get(i);
client.sendMessage(tmp);
}
Message_Array.removeFirst();
isClear = Message_Array.size() > 0 ? false : true;
}
}
}
}
//--- CreateServerThread
class CreateServerThread extends Thread
{
private Socket client;
private BufferedReader in;
private PrintWriter out;
private String Username;
public CreateServerThread(Socket s) throws IOException
{
client = s;
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
out.println("--- Welcome to this chatroom ---");
out.println("Input your nickname:");
start();
}
public void sendMessage(String msg)
{
out.println(msg);
}
public void run()
{
try
{
int flag = 0;
Thread_Counter++;
String line = in.readLine();
while (!line.equals("bye"))
{
if (line.equals("l"))
{
out.println(listOnlineUsers());
line = in.readLine();
continue;
}
if (flag++ == 0)
{
Username = line;
User_List.add(Username);
out.println(listOnlineUsers());
Threader.add(this);
pushMessage("[< " + Username + " come on in >]");
}
else
{
pushMessage("<" + Username + ">" + line);
}
line = in.readLine();
}
out.println("--- See you, bye! ---");
client.close();
}
catch (IOException e)
{}
finally
{
try
{
client.close();
}
catch (IOException e)
{}
Thread_Counter--;
Threader.remove(this);
User_List.remove(Username);
pushMessage("[< " + Username + " left>]");
}
}
private String listOnlineUsers()
{
String s ="-+- online list -+-\015\012";
for (int i = 0; i < User_List.size(); i++)
{
s += "[" + User_List.get(i) + "]\015\012";
}
s += "-+---------------------+-";
return s;
}
private void pushMessage(String msg)
{
Message_Array.addLast(msg);
isClear = false;
}
}
}
screen.width-333)this.width=screen.width-333;" border=0>這就是程序運(yùn)行后,多用戶(hù)登陸并且輸入信息后的屏幕。實(shí)現(xiàn)了信息的實(shí)時(shí)廣播。用戶(hù)輸入"l"就可以列出在線人員表。
相關(guān)推薦:計(jì)算機(jī)等級(jí)考試二級(jí)Java經(jīng)典算法大全匯總北京 | 天津 | 上海 | 江蘇 | 山東 |
安徽 | 浙江 | 江西 | 福建 | 深圳 |
廣東 | 河北 | 湖南 | 廣西 | 河南 |
海南 | 湖北 | 四川 | 重慶 | 云南 |
貴州 | 西藏 | 新疆 | 陜西 | 山西 |
寧夏 | 甘肅 | 青海 | 遼寧 | 吉林 |
黑龍江 | 內(nèi)蒙古 |