版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、 網(wǎng)絡(luò)通信編程課程論文1、面向socket編程1.1. 實(shí)驗(yàn)?zāi)康模?1.1.1理解SOCKET的基本原理; 1.1.2學(xué)會(huì)面向SOCKET編程的代碼編寫及理解各語句內(nèi)容; 1.1.3掌握面向SOCKET編程的具體應(yīng)用。1.2. 實(shí)驗(yàn)要求: 1.2.1建立兩個(gè)獨(dú)立的面向SOCKET編程的JAVA工程,用于服務(wù)器和客戶端系統(tǒng); 1.2.2建立SOCKET的JAVA類,并能正確運(yùn)行且能實(shí)現(xiàn)SOCKET通信; 1.2.3對(duì)JAVA類的功能進(jìn)行拓廣,使SOCKET用于某一具體的應(yīng)用。1.3. 實(shí)驗(yàn)內(nèi)容 1.3.1.建立服務(wù)器端工程和三個(gè)JAVA類,類程序的原代碼為:import java.io.*;im
2、port .*;import java.util.*;public class ChatServer public static void main(String args) ServerSocket server=null; Socket you=null; Hashtable peopleList; peopleList=new Hashtable(); while(true) try server=new ServerSocket(6666); catch(IOException e1) System.out.println(正在監(jiān)聽); try you=server.a
3、ccept(); InetAddress address=you.getInetAddress(); System.out.println(用戶的IP:+address); catch (IOException e) if(you!=null) Server_thread peopleThread=new Server_thread(you,peopleList); peopleThread.start(); else continue; class Server_thread extends Thread String name=null,sex=null; Socket socket=nu
4、ll; File file=null; DataOutputStream out=null; DataInputStream in=null; Hashtable peopleList=null; Server_thread(Socket t,Hashtable list) peopleList=list; socket=t; try in=new DataInputStream(socket.getInputStream(); out=new DataOutputStream(socket.getOutputStream(); catch (IOException e) public voi
5、d run() while(true) String s=null; try s=in.readUTF(); if(s.startsWith(姓名:) name=s.substring(s.indexOf(:)+1,s.indexOf(性別); sex=s.substring(s.lastIndexOf(:)+1); boolean boo=peopleList.containsKey(name); if(boo=false) peopleList.put(name,this); out.writeUTF(可以聊天:); Enumeration enu=peopleList.elements(
6、); while(enu.hasMoreElements() Server_thread th=(Server_thread)enu.nextElement(); th.out.writeUTF(聊天者:+name+性別+sex); if(th!=this) out.writeUTF(聊天者:++性別+th.sex); else out.writeUTF(不可以聊天:); else if(s.startsWith(公共聊天內(nèi)容:) String message=s.substring(s.indexOf(:)+1); Enumeration enu=peopleList.elem
7、ents(); while(enu.hasMoreElements() (Server_thread)enu.nextElement().out.writeUTF(聊天內(nèi)容:+message); else if(s.startsWith(用戶離開:) Enumeration enu=peopleList.elements(); while(enu.hasMoreElements() try Server_thread th=(Server_thread)enu.nextElement(); if(th!=this&th.isAlive() th.out.writeUTF(用戶離線:+name)
8、; catch(IOException eee) peopleList.remove(name); socket.close(); System.out.println(name+用戶離開了); break; else if(s.startsWith(私人聊天內(nèi)容:) String 悄悄話=s.substring(s.indexOf(:)+1,s.indexOf(#); String toPeople=s.substring(s.indexOf(#)+1); Server_thread toThread=(Server_thread)peopleList.get(toPeople); if(t
9、oThread!=null) toThread.out.writeUTF(私人聊天內(nèi)容:+悄悄話); else out.writeUTF(私人聊天內(nèi)容:+toPeople+已經(jīng)離線); catch(IOException ee) Enumeration enu=peopleList.elements(); while(enu.hasMoreElements() try Server_thread th=(Server_thread)enu.nextElement(); if(th!=this&th.isAlive() th.out.writeUTF(用戶離線:+name); catch(IOE
10、xception eee) peopleList.remove(name); try socket.close(); catch(IOException eee) System.out.println(name+用戶離開了); break; 1.3.2.建立客戶端工程和JAVA類,類程序的原代碼為:import java.awt.*;import java.io.*;import .*;import java.applet.*;import java.util.Hashtable;public class ClientChat extends Applet implements
11、 Runnable Socket socket=null; DataInputStream in=null; DataOutputStream out=null; InputNameTextField 用戶提交昵稱界面=null; ChatArea 用戶聊天界面=null; Hashtable listTable; Label 提示條; Panel north, center; Thread thread; public void init() int width=getSize().width; int height=getSize().height; listTable=new Hasht
12、able(); setLayout(new BorderLayout(); 用戶提交昵稱界面=new InputNameTextField(listTable); int h=用戶提交昵稱界面.getSize().height; 用戶聊天界面=new ChatArea(,listTable,width,height-(h+5); 用戶聊天界面.setVisible(false); 提示條=new Label(正在連接到服務(wù)器,請(qǐng)稍等.,Label.CENTER); 提示條.setForeground(Color.red); north=new Panel(new FlowLayout(Flow
13、Layout.LEFT); center=new Panel(); north.add(用戶提交昵稱界面); north.add(提示條); center.add(用戶聊天界面); add(north,BorderLayout.NORTH); add(center,BorderLayout.CENTER); validate(); public void start() if(socket!=null&in!=null&out!=null) try socket.close(); in.close(); out.close(); 用戶聊天界面.setVisible(false); catch(
14、Exception ee) try socket = new Socket(this.getCodeBase().getHost(), 6666); in=new DataInputStream(socket.getInputStream(); out=new DataOutputStream(socket.getOutputStream(); catch (IOException ee) 提示條.setText(連接失敗); if(socket!=null) InetAddress address=socket.getInetAddress(); 提示條.setText(連接:+addres
15、s+成功); 用戶提交昵稱界面.setSocketConnection(socket,in,out); north.validate(); if(thread=null) thread=new Thread(this); thread.start(); public void stop() try socket.close(); thread=null; catch(IOException e) this.showStatus(e.toString(); public void run() while(thread!=null) if(用戶提交昵稱界面.get能否聊天()=true) 用戶聊天
16、界面.setVisible(true); 用戶聊天界面.setName(用戶提交昵稱界面.getName(); 用戶聊天界面.setSocketConnection(socket,in,out); 提示條.setText(祝聊天愉快!); center.validate(); break; try Thread.sleep(100); catch(Exception e) 1.3.3.調(diào)試使以上兩個(gè)工程能正常運(yùn)行,使服務(wù)端和客戶端能正常通信登陸界面:聊天界面:1.4. 實(shí)驗(yàn)心得其實(shí),簡(jiǎn)單的分析一下,就可以看出客戶和服務(wù)通訊的主要通道就是Socket本身,而服務(wù)器通過accept方法就是同意和客
17、戶建立通訊.這樣當(dāng)客戶建立Socket的同時(shí)。服務(wù)器也會(huì)使用這一根連線來先后通訊,那么既然如此只要我們存在多條連線就可以了2. 基于UDP編程實(shí)驗(yàn)2.1. 實(shí)驗(yàn)?zāi)康模?.1.1理解UDP及基于數(shù)據(jù)報(bào)通信的基本原理;2.1.2學(xué)會(huì)基于UDP編程的代碼編寫及理解各語句內(nèi)容;2.1.3掌握基于UDP編程的具體應(yīng)用。2.2實(shí)驗(yàn)要求:2.2.1建立兩個(gè)獨(dú)立的基于UDP編程的JAVA工程,用于服務(wù)器和客戶端系統(tǒng);2.2.2建立UDP的JAVA類,并能正確運(yùn)行且能實(shí)現(xiàn)數(shù)據(jù)報(bào)通信;2.2.3對(duì)JAVA類的功能進(jìn)行拓廣,使基于UDP編程用于某一具體的應(yīng)用。2.3實(shí)驗(yàn)內(nèi)容:UDPserver關(guān)鍵代碼: publi
18、c UDPServer() addTableHead(); JFrame frame = new JFrame(); JPanel panel = new JPanel(); frame.setSize(300, 150); select_dir = new JButton(選擇文件夾); msg_lb = new JLabel(服務(wù)已停止); path_lb = new JLabel(路徑); port_lb = new JLabel(端口); path_tf = new JTextField(20); path_tf.setEditable(false); port_tf = new JT
19、extField(20); start_server = new JButton(啟動(dòng)服務(wù)); stop_server = new JButton(停止服務(wù)); select_dir.setText(選擇文件夾); /給按鈕添加事件,選擇客戶端可下載的文件所在的文件夾 select_dir.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(
20、JFileChooser.DIRECTORIES_ONLY); int value = chooser.showOpenDialog(null); if (value = JFileChooser.APPROVE_OPTION) path_tf.setText(chooser.getSelectedFile().getPath(); ); start_server.addActionListener(new ActionListener() /啟動(dòng)服務(wù)事件 public void actionPerformed(java.awt.event.ActionEvent evt) int liste
21、n_port = 3000; if (!port_tf.getText().trim().equals() listen_port = Integer.parseInt(port_tf.getText().trim(); udp_server = new UDPServer(path_tf.getText(), listen_port); udp_server.startServer(); msg_lb.setText(服務(wù)已啟動(dòng)); ); stop_server.addActionListener(new ActionListener() public void actionPerforme
22、d(java.awt.event.ActionEvent evt) udp_server.stopServer(); msg_lb.setText(服務(wù)已關(guān)閉); ); panel.add(path_lb); panel.add(path_tf); panel.add(select_dir); panel.add(start_server); panel.add(stop_server); panel.add(msg_lb); frame.add(panel); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.E
23、XIT_ON_CLOSE); frame.setVisible(true); public class MyProgressBar extends JProgressBar implements TableCellRenderer public MyProgressBar(int min, int max) super(min, max); this.setBackground(Color.white); this.setForeground(Color.CYAN); public Component getTableCellRendererComponent( JTable table, O
24、bject value, boolean isSelected, boolean hasFocus, int row, int column) setValue(Integer.parseInt(String.valueOf(value); return this; public class ProgressCellModel extends DefaultTableCellRenderer public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolea
25、n hasFocus, int row, int column) Component cell = super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); TableColumn tableColumn = table.getColumnModel().getColumn(column); String strColumnHeader = String.valueOf(tableColumn.getHeaderValue(); if (strColumnHeader.equal
26、s(進(jìn)度) MyProgressBar progressbar = new MyProgressBar(0, 100); tableColumn.setCellRenderer(progressbar); return cell; void startServer() /創(chuàng)建ServerSocket try if (server = null) server = new DatagramSocket(server_port); if (file_server = null) file_server = new DatagramSocket(file_port); /啟動(dòng)了一個(gè)線程,來等待客戶端
27、的鏈接 new ConnThread().start(); new FileThread().start(); catch (IOException e) e.printStackTrace(); private class ConnThread extends Thread public void run() while (flag) try byte buffer = new byte256; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); server.receive(packet); putFileL
28、ist(packet); catch (IOException e) e.printStackTrace(); /把文件夾里的文件列表傳給客戶端 private void putFileList(DatagramPacket packet) /取得連接的地址和端口 InetAddress address = packet.getAddress(); int port = packet.getPort(); File file = new File(file_path); String file_names = file.list(); String s = ; for (String str
29、: file_names) s = s + str + ; byte b = s.getBytes(); packet = new DatagramPacket(b, b.length, address, port); try server.send(packet); catch (IOException ex) ex.printStackTrace(); private class FileThread extends Thread public void run() while (flag) try byte buffer = new byte256; DatagramPacket pac
30、ket = new DatagramPacket(buffer, buffer.length); file_server.receive(packet); /這里啟動(dòng)一個(gè)線程,等待客戶端獲取文件 new SendThread(packet).start(); new TableThread().start(); catch (IOException e) e.printStackTrace(); /線程類,等待客戶機(jī)下載文件 private class SendThread extends Thread private DatagramPacket packet; public SendThr
31、ead(DatagramPacket packet) this.packet = packet; public void run() download(packet); private void download(DatagramPacket packet) try String file_str = new String(packet.getData(), 0, packet.getLength(); File file = new File(file_path, file_str); FileInputStream filein = new FileInputStream(file); b
32、yte b = new byte1024; long i = 0; /已傳輸?shù)淖止?jié)數(shù) String l = ; /已K來計(jì)算已傳輸?shù)臄?shù)量 String per = ; /顯示百分比 int length = 0; table_frame.setSize(400, 400); table_frame.add(pane); Vector cell = new Vector(); cell.add(packet.getAddress(); cell.add(file_str); cell.add(l); cell.add(per); cell.add(傳輸中.); row.add(cell); ta
33、bleModel.setDataVector(row, head); table.setModel(tableModel); table.setDefaultRenderer( Class.forName(java.lang.Object), cellModel); table_frame.setVisible(true); /取得連接的地址和端口 InetAddress address = packet.getAddress(); int port = packet.getPort(); while (length = filein.read(b) != -1) packet = new D
34、atagramPacket(b, length, address, port); try file_server.send(packet); catch (IOException ex) Logger.getLogger(UDPServer.class.getName().log(Level.SEVERE, null, ex); i = i + length; l = i / 1024 + K; per = (i * 100 / file.length() + %; cell.set(2, l); cell.set(3, (int) (i * 100 / file.length(); cell
35、.set(4, per); cell.set(5, 傳輸中.); filein.close(); cell.set(5, 傳輸完畢); catch (Exception e) System.out.println(Error handling a client: + e); /線程,刷新table private class TableThread extends Thread public void run() while (true) table.repaint(); public void stopServer() flag = false; public static void mai
36、n(String args) UDPServer server = new UDPServer(); UDPClient關(guān)鍵代碼public UDPClient(String host_ip, int host_port) System.out.println(host_ip + , + host_port); this.host_ip = host_ip; this.host_port = host_port; public UDPClient() setSize(350, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPane
37、l panel = new JPanel(); JFrame frame = new JFrame(); ip_lb = new JLabel(IP); port_lb = new JLabel(端口); ip_tf = new JTextField(20); port_tf = new JTextField(20); link_bt = new JButton(連接); ip_tf = new JTextField(); port_tf = new JTextField(3000); /讀取服務(wù)器的文件列表 link_bt.addActionListener(new Act
38、ionListener() public void actionPerformed(ActionEvent e) String ip = ip_tf.getText().trim(); int port = Integer.parseInt(port_tf.getText().trim(); client = new UDPClient(ip, port); client.connect(); ); /創(chuàng)建窗口 panel.add(ip_lb); panel.add(ip_tf); panel.add(port_lb); panel.add(port_tf); panel.add(link_b
39、t); frame.add(panel); frame.setResizable(false); frame.setSize(270, 120); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); /連接到服務(wù)器端 public void connect() try client_socket = new DatagramSocket(); byte b = new byte1024; packet = new DatagramPacket(b, b.length, InetAddress
40、.getByName(host_ip), host_port); client_socket.send(packet); packet = new DatagramPacket(b, b.length); client_socket.receive(packet); String files = new String(packet.getData(), 0, packet.getLength(); if (!files.trim().equals() showFileList(files); client_socket.close(); catch (UnknownHostException
41、e) System.out.println(Error setting up socket connection: unknown host at + host_ip + : + host_port); catch (IOException e) System.out.println(Error setting up socket connection: + e); /創(chuàng)建一個(gè)文件列表的窗口 private void showFileList(String files) JFrame frame = new JFrame(); frame.setSize(400, 400); JTable t
42、able = new JTable(); createTable(table, files); JScrollPane pane = new JScrollPane(table); frame.add(pane); JButton get_file = new JButton(傳輸文件); /按鈕事件,下載文件用的 get_file.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) /啟動(dòng)一個(gè)下載線程,以免阻塞主線程 new DownFile().start(); ); frame
43、.add(get_file, BorderLayout.SOUTH); frame.setVisible(true); /創(chuàng)建文件列表 private void createTable(JTable table, String files) DefaultTableModel tableModel = new DefaultTableModel(); final Vector row = new Vector(); Vector cell; String f = files.split(;); for (String str : f) cell = new Vector(); cell.add(str); row.add(cell); Vector head = new Vector(); head.add(文件); tableModel.setDataVector(row, head); table.setModel(tableModel); ListSelectionModel model = table.getSelectionModel(); mod
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年蘭陵縣神山鎮(zhèn)公開選拔“青年干部、青年黨員、青年人才”備考題庫及參考答案詳解1套
- 2026年常州市衛(wèi)生健康委員會(huì)直屬事業(yè)單位公開招聘高層次、緊缺專業(yè)人才14人備考題庫帶答案詳解
- 2026年北礦機(jī)電科技有限責(zé)任公司招聘?jìng)淇碱}庫及答案詳解1套
- 2026年APP原型設(shè)計(jì)合同協(xié)議
- 2026年農(nóng)村農(nóng)村勞動(dòng)力轉(zhuǎn)移合同協(xié)議
- 2025年高職(數(shù)字媒體藝術(shù)設(shè)計(jì))影視后期特效制作綜合測(cè)試題及答案
- 2025年高職(市場(chǎng)營(yíng)銷)整合營(yíng)銷傳播實(shí)訓(xùn)綜合測(cè)試題及答案
- 2026年窗簾布藝生產(chǎn)合作合同協(xié)議
- 2026年機(jī)器翻譯校對(duì)合同
- 河道流域環(huán)境整治方案
- DL-T5394-2021電力工程地下金屬構(gòu)筑物防腐技術(shù)導(dǎo)則
- 國(guó)家開放大學(xué) -理工英語3(閉卷)
- 成都市地方政府專項(xiàng)債申報(bào)操作指南
- 2024年4月自考00840第二外語(日語)試題
- 《繼電保護(hù)智能運(yùn)維檢修 第5部分:在線監(jiān)測(cè)站端信息描述》編制說明
- 社會(huì)實(shí)踐-形考任務(wù)一-國(guó)開(CQ)-參考資料
- 趣味實(shí)驗(yàn)牛頓擺
- 水泥生料配料方案解析
- 洗煤廠安全培訓(xùn)課件
- 水電站壓力管道課件
- 鐵總建設(shè)201857號(hào) 中國(guó)鐵路總公司 關(guān)于做好高速鐵路開通達(dá)標(biāo)評(píng)定工作的通知
評(píng)論
0/150
提交評(píng)論