計算機網(wǎng)絡(luò)課程設(shè)計UDP聊天室代碼_第1頁
計算機網(wǎng)絡(luò)課程設(shè)計UDP聊天室代碼_第2頁
計算機網(wǎng)絡(luò)課程設(shè)計UDP聊天室代碼_第3頁
計算機網(wǎng)絡(luò)課程設(shè)計UDP聊天室代碼_第4頁
計算機網(wǎng)絡(luò)課程設(shè)計UDP聊天室代碼_第5頁
已閱讀5頁,還剩25頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1、計算網(wǎng)絡(luò)UDP聊天室 學 院 計算機學院 專 業(yè) 軟件工程 年級班別 2011級1班 學 號 學生姓名 指導教師 許青林 成 績 .實驗?zāi)康?UDP是無鏈接的通信方式,通信開銷小,利用UDP實現(xiàn)聊天系統(tǒng)。通過實驗掌握UDP的工作原理及應(yīng)用方法。.實驗要求 1、采用多線程技術(shù),多用戶同時在線。 2、實現(xiàn)群聊功能,一個人發(fā)消息多人可收到。 3、用JAVA實現(xiàn) UDP開發(fā)模型如下: .系統(tǒng)結(jié)構(gòu)聊天系統(tǒng)分為服務(wù)器端和客戶端。服務(wù)器程序作為一個中轉(zhuǎn)站,所有客戶端都只與服務(wù)器進行通信。如圖:.程序設(shè)計服務(wù)器端:服務(wù)器與客戶間通過套接口Socket連接。在java中使用套接口相當簡單,Java API為處理

2、套接口的通信提供了一個類.Socket.,使得編寫網(wǎng)絡(luò)應(yīng)用程序相對容易服務(wù)器采用多線程以滿足多用戶的請求,服務(wù)端主要用到InetAddress,  DatagramSocket, DatagramPacket三個類; InetAddress用于描述和包裝一個Internet IP地址;DatagramSocket用于接收和發(fā)送UDP的Socket實例;DatagramPacket用于處理報文,它將Byte數(shù)組、目標地址、目標端口等數(shù)據(jù)包裝成報文或者將報文拆卸成Byte數(shù)組??蛻舳耍嚎蛻舳耸且粋€Java Application程序,客戶通過Socket 建立與服務(wù)器的連接。主

3、要用到InetAddress,  DatagramSocket, DatagramPacket三個類三個類。界面設(shè)計:客戶端UI設(shè)計:Chat Boxes有五個輸入框,包括本機端口,服務(wù)器端口,本機IP地址,服務(wù)器IP地址輸入以及消息輸入框,依次為Personal port,Server port,Nickname和Server IP以及send按鈕左旁的輸入框,且在輸入的消息中自動獲取本機時間,然后和發(fā)送消息一起打包發(fā)到服務(wù)器,服務(wù)器接收后發(fā)到客戶端。服務(wù)器IP不為空。 Server UI設(shè)計:Server chat boxes有兩個輸入框,分別是服務(wù)器端口(Server port

4、)和客戶端端口(Personal port)和一個連接按鈕(Connect);.代碼:(按照下面的格式創(chuàng)建相應(yīng)的java文件,將代碼粘貼復(fù)制即可)1. Sendmessage,javapackage chatboxes;import java.io.Serializable;import .InetAddress;public class Sendmessage implements Serializable/* * */private static final long serialVersionUID = 1L;private InetAddress addr;private InetAd

5、dress destaddr;private String name;private String msg;public Sendmessage(InetAddress addr, InetAddress destaddr, String name, String msg) this.addr = addr;this.destaddr = destaddr; = name;this.msg = msg;public InetAddress getAddr() return addr;public InetAddress getDestaddr() return destadd

6、r;public String getName() return name;public String getMsg() return msg;2. Serverchar.javapackage chatboxes;import java.awt.BorderLayout;import java.awt.Container;import java.awt.FlowLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.

7、io.BufferedInputStream;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import .DatagramPacket;import .DatagramSocket;import .InetAddress;import .MulticastSocket;import .SocketExcept

8、ion;import .UnknownHostException;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;import java.util.List;import java.util.ListIterator;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JScrollPan

9、e;import javax.swing.JTextArea;import javax.swing.JTextField;public class Serverchat implements Runnable, ActionListenerprivate List<InetAddress> addList;JTextArea showArea;JLabel lbl1, lbl2;JTextField sendPortText, receivePortText;JFrame mainJframe;JButton startBtn;JScrollPane JSPane;JPanel p

10、ane1, pane2;Container con;Thread thread = null;DatagramPacket sendPack, receivePack;DatagramSocket sendSocket, receiveSocket;private int sendPort, receivePort;private byte inBuf, outBuf;private MulticastSocket multiSocket = null;public Serverchat() throws UnknownHostException addList = new ArrayList

11、<InetAddress>();mainJframe = new JFrame("Server chat boxes");con = mainJframe.getContentPane();showArea = new JTextArea();showArea.setEditable(false);showArea.setLineWrap(true);lbl1 = new JLabel("Server port:");lbl2 = new JLabel("Personal port:");sendPortText = ne

12、w JTextField();sendPortText.setColumns(5);receivePortText = new JTextField();receivePortText.setColumns(5);startBtn = new JButton("Connect");startBtn.addActionListener(this);pane1 = new JPanel();pane1.setLayout(new GridLayout(3,2);pane1.add(lbl1);pane1.add(receivePortText);pane1.add(lbl2);

13、pane1.add(sendPortText);pane1.add(startBtn);JSPane = new JScrollPane(showArea);pane2 = new JPanel();pane2.setLayout(new FlowLayout();con.add(pane1, BorderLayout.NORTH);con.add(JSPane, BorderLayout.CENTER);con.add(pane2, BorderLayout.SOUTH);mainJframe.setSize(600,600);mainJframe.setVisible(true);main

14、Jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);showArea.append("=" +"=n");showArea.append("=" +"=n");public static void main(String args) try new Serverchat(); catch (UnknownHostException e) / TODO Auto-generated catch blocke.printStackTrace();Overridep

15、ublic void run() Sendmessage msg;while (true) try receiveSocket.receive(receivePack);ByteArrayInputStream byteStream = new ByteArrayInputStream(receivePack.getData();ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(byteStream); Object o = is.readObject();msg = (Sendmessage) o;is.

16、close();InetAddress test = receivePack.getAddress();if(!addList.contains(test)addList.add(test);for(InetAddress iaddr : addList)sendPack = new DatagramPacket(receivePack.getData(), receivePack.getData().length, iaddr,sendPort);sendSocket.send(sendPack);showArea.append(msg.getAddr() + ":n"

17、+ msg.getMsg() + "n"); catch (IOException el) showArea.append(el.getMessage()+"n"); catch (ClassNotFoundException e) / TODO Auto-generated catch blocke.printStackTrace();Overridepublic void actionPerformed(ActionEvent e) try if (e.getSource() = startBtn) if(sendPortText.getText()

18、.equals("")sendPort = 10087;elsesendPort = Integer.parseInt(sendPortText.getText();if(receivePortText.getText().equals("")receivePort = 10086;elsereceivePort = Integer.parseInt(receivePortText.getText();inBuf = new byte16384;sendSocket = new DatagramSocket();receivePack = new Dat

19、agramPacket(inBuf, inBuf.length);receiveSocket = new DatagramSocket(receivePort);thread = new Thread(this);thread.setPriority(Thread.MIN_PRIORITY);thread.start();startBtn.setEnabled(false);else catch (SocketException e1) showArea.append("System Error"+e1.getMessage()+"n"); catch

20、(IOException e1) showArea.append("System Error"+e1.getMessage()+"n");3. UIchat.javapackage chatboxes;import java.awt.BorderLayout;import java.awt.Container;import java.awt.FlowLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener

21、;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import .DatagramPacket;import .DatagramSocket;import .InetAdd

22、ress;import .SocketException;import .UnknownHostException;import java.text.SimpleDateFormat;import java.util.Date;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JT

23、extField;public class UIchat implements Runnable, ActionListener JTextArea showArea;JLabel lbl1, lbl2, lbl3, lbl4;JTextField msgText, sendPortText, receivePortText, IPAddressText, name;JFrame mainJframe;JButton sendBtn, startBtn;JScrollPane JSPane;JPanel pane1, pane2;Container con;Thread thread = nu

24、ll;DatagramPacket sendPack, receivePack;DatagramSocket sendSocket, receiveSocket;private String username;private InetAddress sendIP;private int sendPort, receivePort;private byte inBuf, outBuf;public UIchat() mainJframe = new JFrame("Chat Boxes");con = mainJframe.getContentPane();showArea

25、= new JTextArea();showArea.setEditable(false);showArea.setLineWrap(true);lbl1 = new JLabel("Personal port:");lbl2 = new JLabel("Server port:");lbl3 = new JLabel("Server IP:");lbl4 = new JLabel("Nickname:");sendPortText = new JTextField();sendPortText.setColumn

26、s(15);receivePortText = new JTextField();receivePortText.setColumns(15);name = new JTextField();name.setColumns(15);IPAddressText = new JTextField();IPAddressText.setColumns(15);startBtn = new JButton("Connect");startBtn.addActionListener(this);pane1 = new JPanel();pane1.setLayout(new Grid

27、Layout(5,2);pane1.add(lbl1);pane1.add(receivePortText);pane1.add(lbl2);pane1.add(sendPortText);pane1.add(lbl3);pane1.add(IPAddressText);pane1.add(lbl4);pane1.add(name);pane1.add(startBtn);JSPane = new JScrollPane(showArea);msgText = new JTextField();msgText.setColumns(40);msgText.setEditable(false);

28、msgText.addActionListener(this);sendBtn = new JButton("Send");sendBtn.setEnabled(false);sendBtn.addActionListener(this);pane2 = new JPanel();pane2.setLayout(new FlowLayout();pane2.add(msgText);pane2.add(sendBtn);con.add(pane1, BorderLayout.NORTH);con.add(JSPane, BorderLayout.CENTER);con.ad

29、d(pane2, BorderLayout.SOUTH);mainJframe.setSize(700, 600);mainJframe.setVisible(true);mainJframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);showArea.append("=" +"=n");showArea.append(" Please Keep The Ports Of The Chat Boxes Up With The Ports Of Server chat boxesn"+

30、" *The Nickname Is The IP Of Your Personal Computer IP*n"+" *The Server IP Should Not Be Null!*n");showArea.append("=" +"=n");public static void main(String args) new UIchat();Overridepublic void actionPerformed(ActionEvent e) try if (e.getSource() = startBtn)

31、 inBuf = new byte16384;if(sendPortText.getText().equals("")sendPort = 10086;elsesendPort = Integer.parseInt(sendPortText.getText();if(receivePortText.getText().equals("")receivePort = 10087;elsereceivePort = Integer.parseInt(receivePortText.getText();if(name.getText().equals(&quo

32、t;")username = InetAddress.getLocalHost().toString();elseusername = name.getText();sendIP = InetAddress.getByName(IPAddressText.getText();sendSocket = new DatagramSocket();receivePack = new DatagramPacket(inBuf, inBuf.length);receiveSocket = new DatagramSocket(receivePort);thread = new Thread(t

33、his);thread.setPriority(Thread.MIN_PRIORITY);thread.start();startBtn.setEnabled(false);sendBtn.setEnabled(true);msgText.setEditable(true);else String msg1 = msgText.getText();SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String msg=format.format(new Date()+" : &q

34、uot;+msg1;Sendmessage message = new Sendmessage(InetAddress.getLocalHost(),sendIP,username,msg);ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; oos = new ObjectOutputStream(baos); oos.writeObject(message); oos.flush(); outBuf = baos.toByteArray();sendPack = n

35、ew DatagramPacket(outBuf, outBuf.length, sendIP,sendPort);sendSocket.send(sendPack);msgText.setText(null); catch (UnknownHostException e1) showArea.append("System Error"+e1.getMessage()+"n"); catch (SocketException e1) showArea.append("System Error"+e1.getMessage()+"n")

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論