一個用Java編寫的簡單聊天室 用來學習Socket編程__演算法

來源:互聯網
上載者:User

/* *Create on Jan 29, 2009 *Copyright 2009 Quasar20063501.All Rights reserved * *weizhaozhe */ package client; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.*; public class ChatClient extends Frame { private boolean connected = false; private DataOutputStream dos = null; private DataInputStream dis = null; private static final long serialVersionUID = 1L; private Socket s = null; private TextField tfWords = null; private TextArea taShow = null; public static void main(String args[]) { ChatClient cc = new ChatClient(); cc.launchFrame(); cc.Listen(); } public void launchFrame() { try { s = new Socket(InetAddress.getByName("localhost"), 8888); connected = true; dos = new DataOutputStream(s.getOutputStream()); dis = new DataInputStream(s.getInputStream()); } catch (IOException ioe) { System.out.println("伺服器串連失敗。"); ioe.printStackTrace(); } this.tfWords = new TextField(); this.taShow = new TextArea(); this.setTitle("Chatroom Client"); this.setLocation(700, 50); this.add(tfWords, BorderLayout.SOUTH); this.add(taShow, BorderLayout.NORTH); this.setSize(200, 250); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { try { connected = false; dos.writeUTF("###Exit###"); dos.flush(); close(); System.exit(0); } catch (IOException ioe) { System.out.println("訊息發送出錯。"); ioe.printStackTrace(); } } }); this.setVisible(true); this.tfWords.addActionListener(new TFWordsListener()); } public void Listen() { new Thread(new ListenThread()).start(); } public void close() { try { if (dos != null) dos.close(); if (s != null) s.close(); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("用戶端斷開時出錯。"); System.exit(-1); } } public class ListenThread implements Runnable{ public void run(){ while (connected) { try { String back = dis.readUTF(); //阻塞IO taShow.append(back); }catch(SocketException se){ System.out.println("謝謝使用。"); }catch (IOException e) { System.out.println("資料丟失。"); e.printStackTrace(); } } } } private class TFWordsListener implements ActionListener { public void actionPerformed(ActionEvent e) { String words = tfWords.getText().trim(); taShow.append("ME: " + words + "/n"); tfWords.setText(""); try { dos.writeUTF(words); } catch (IOException ioe) { System.out.println("發送出錯。"); ioe.printStackTrace(); } } } } 代碼如下:

伺服器端:

 /* *Create on Jan 29, 2009 *Copyright 2009 Quasar20063501.All Rights reserved * *weizhaozhe */ package server; /** * 這個聊天室程式是基於TCP Socket的,其中,為了消除IO阻塞,採用了多線程的方式。 * * @author Quasar20063501 * @since Jan 29, 2009 * */ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.*; import java.util.List; import java.util.ArrayList; public class ChatServer { private List<Client> clients = new ArrayList<Client>(); private boolean started = false; private ServerSocket ss = null; private Client c = null; public ChatServer() { try { ss = new ServerSocket(8888); started = true; } catch (IOException ioe) { System.out.println("對不起,伺服器不能啟動。"); ioe.printStackTrace(); System.exit(-1); } } public void start() { try { Socket s = this.getSs().accept(); System.out.println("Here comes a client! "); if (s != null) { c = this.new Client(s, true); this.clients.add(c); new Thread(c).start(); // 線程始終沒能停止。。。? c = null; } } catch (IOException e) { System.out.println("串連錯誤。"); e.printStackTrace(); } } public boolean isStarted() { return started; } public void setStarted(boolean started) { this.started = started; } public ServerSocket getSs() { return ss; } public void setSs(ServerSocket ss) { this.ss = ss; } public List<Client> getClients() { return clients; } public void setClients(List<Client> clients) { this.clients = clients; } public static void main(String args[]) { ChatServer cs = new ChatServer(); while (cs.isStarted()) { cs.start(); } } private class Client implements Runnable { private boolean connected = false; private Socket s = null; private DataInputStream dis = null; private DataOutputStream dos = null; public Client(Socket s, boolean connected) { this.s = s; this.connected = connected; } public void run() { InetAddress ip = null; int port = 9999; try { if (connected) { dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); ip = s.getInetAddress(); port = s.getPort(); } while (connected) { String line = dis.readUTF(); if (line.equals("###Exit###")) { getClients().remove(this); // 當接收到推出的訊息,移除用戶端記錄 line = "Bye-Bye!"; connected = false; } System.out.println("From: (" + ip.toString() + ":" + port + "): " + line); for (int i = 0; i < getClients().size(); i++) { if (this.equals(getClients().get(i))) { continue; } else { getClients().get(i).dos.writeUTF("From: (" + ip.toString() + ":" + port + "): " + line + "/n"); } } } } catch (IOException ioe) { System.out.println("用戶端串連出錯。"); ioe.printStackTrace(); } } } }

SOCKET 網路編程概要:

Socket又稱為通訊端,是兩個程式進行雙向資料轉送的網路通

信的端點,一般由IP + PORT 構成。

(我們編程,通常採用的連接埠是大於1023的小於65535的數,1023之前一般被佔用,如80被HTTP服務其佔用,21被Telnet佔用,23被FTP伺服器佔用等等)

Socket是一種底層的通訊機制,通過Socket的資料是原始的位元組流,必須經過兩端的程式按照協議進行處理和解釋。

其分為兩類,連線導向的TCP/IP通訊,和非串連的UDP資料報通訊,我們的聊天室是採用TCP/IP連線導向編寫的。

使用流程,在伺服器端和用戶端,分別使用ServerSocket和Socket,基本流程如下:

1建立通訊端

2開啟串連的IO

3按照協議讀寫

4關閉資源

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.