已阅读5页,还剩25页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
计算机网络原理实 验 报告 书姓名:XXX班级:XXXXXX学号:XXXXXXXXXXXXXXXXXXXXXX 二0一一年五月 socket编程一、 实验目的本次实验的目的是通过利用Socket编写简单的客户/服务器程序,了解TCP/IP网络的基本通信原理和编程方法,初步掌握TCP/IP网络的传输层上的编程接口(Windows Sockets API),学会利用这些接口来编写简单的网络通信软件。二、 实验内容利用socket编写简单的客户/服务器程序,比如聊天室、文件传输等。三、 实验步骤 思路分析 将服务器与客户端分两部分实现,采用多线程实现多个客户端与服务器端连接 客户端建立一个Socket与服务器端连接,成功后通过这个Socket来发送和接收数据就可以了。 服务器端通过创建一个Socket的Arraylist数组,与指定的本地端口绑定,就可以在端口进行侦听。如果有客户端连接请求,则在数组中选择一个空Socket,将客户端地址赋给这个Socket。然后登录成功的客户就可以在服务器上聊天了。 代码实现 package TCP_chat_room.gui; import java.io.IOException; public class ClientApp public static void main(String args) /* * javax.swing.UIManager$LookAndFeelInfoMetal javax.swing.plaf.metal.MetalLookAndFeel javax.swing.UIManager$LookAndFeelInfoNimbus com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel javax.swing.UIManager$LookAndFeelInfoCDE/Motif com.sun.java.swing.plaf.motif.MotifLookAndFeel javax.swing.UIManager$LookAndFeelInfoWindows com.sun.java.swing.plaf.windows.WindowsLookAndFeel javax.swing.UIManager$LookAndFeelInfoWindows Classic com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel * author Administrator * */ try /使用Nimbus皮肤 UIManager.setLookAndFeel(com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel); /localhost 或 ClientFrame frClientFrame = new ClientFrame(localhost,Server.CHAT_ROOM_PORT); frClientFrame.setConnected(true); frClientFrame.setVisible(true); /如果登录成功 if(frClientFrame.login(222) frClientFrame.receiveMessage(); catch (ClassNotFoundException e) e.printStackTrace(); catch (InstantiationException e) e.printStackTrace(); catch (IllegalAccessException e) e.printStackTrace(); catch (UnsupportedLookAndFeelException e) e.printStackTrace(); catch (IOException e) e.printStackTrace(); package TCP_chat_room.action;import java.awt.AWTException;public class ClientFrameAction extends WindowAdapterprivate ClientFrame frClientFrame;public ClientFrameAction(ClientFrame frClientFrame)this.frClientFrame = frClientFrame;public void windowIconified(WindowEvent e) if(SystemTray.isSupported()final SystemTray system = SystemTray.getSystemTray();Image image = ImageManager.getImage(piScreen.gif);final String toolTip = new String(大家聊天室);final PopupMenu popup = new PopupMenu();final MenuItem miRevert = new MenuItem(Restore);final MenuItem miAddFriends = new MenuItem(Add Friends);final MenuItem miRemoveFriends = new MenuItem(Remove Friends);final MenuItem miModifyFriendsInfo = new MenuItem(Modify Friends Infomation);final MenuItem miSearch = new MenuItem(Search Friends);final MenuItem miExit = new MenuItem(Exit);popup.add(miRevert);popup.addSeparator();popup.add(miAddFriends);popup.add(miRemoveFriends);popup.add(miModifyFriendsInfo);popup.add(miSearch);popup.addSeparator();popup.add(miExit);final TrayIcon icon = new TrayIcon(image,toolTip,popup);try system.add(icon);frClientFrame.setVisible(false); catch (AWTException e1) System.out.print(软件在系统通知区域显示出错);e1.printStackTrace();miRevert.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) system.remove(icon);frClientFrame.setVisible(true);frClientFrame.setState(JFrame.NORMAL););miAddFriends.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) frClientFrame.setVisible(true);frClientFrame.setState(JFrame.NORMAL););miExit.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) windowClosing(null););/不知何用icon.addActionListener(miRevert.getActionListeners()0);public void windowClosing(WindowEvent e) int result = MessageBox.showConfirmMessage(您确定要退出聊天系统吗?);if(result = JOptionPane.YES_OPTION)frClientFrame.disconnect();frClientFrame.setVisible(false);frClientFrame.dispose();/System.exit(0);else/do nothingpackage TCP_chat_room.gui;import java.awt.Color;public class ClientFrame extends JFrame private boolean connected = false;private int port;private String host;private Socket s;private DataInputStream dis;private DataOutputStream dos;public DataInputStream getDis() return dis;public DataOutputStream getDos() return dos;private final JPanel panel = new JPanel();private final JPanel pnlChatArea = new JPanel();private final ImageIcon imageSetting = ImageManager.getIcon(setting.gif);private final JLabel lblSettingImage = new JLabel(imageSetting);private final JPanel pnlSetting = new JPanel();private final JPanel pnlInputArea = new JPanel();private final JButton bnClose = new JButton(关闭);private final JButton bnSend = new JButton(发送);private final JTextArea txtChatArea = new JTextArea(6,15);private final JTextArea txtInputArea = new JTextArea(2,15);private final Dimension minDimension = new Dimension(300, 413);public boolean isConnected() return connected;public void setConnected(boolean connected) this.connected = connected;public JTextArea getTxtChatArea() return txtChatArea;public JTextArea getTxtInputArea() return txtInputArea;public ClientFrame(String host,int port) throws IOException this.host = host;this.port = port;s = new Socket(host,port);dos = new DataOutputStream(s.getOutputStream();dis = new DataInputStream(s.getInputStream();initComponents();private void initComponents() this.setTitle(大家聊天室);this.setSize(minDimension);this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);getContentPane().setLayout(null);panel.setBounds(0, 0, 292, 379);getContentPane().setBackground(Color.LIGHT_GRAY);getContentPane().add(panel);panel.setLayout(null);pnlChatArea.setBounds(0, 0, 292, 226);JScrollPane jspChatArea = new JScrollPane(txtChatArea);jspChatArea.setAutoscrolls(false);pnlChatArea.add(jspChatArea);panel.add(pnlChatArea);pnlChatArea.setLayout(null);txtChatArea.setLineWrap(true);txtChatArea.setEditable(false);/pnlChatArea.setBounds(10, 10, 272, 206);jspChatArea.setBounds(10, 10, 272, 206);pnlSetting.setBounds(0, 235, 292, 45);pnlSetting.add(lblSettingImage);panel.add(pnlSetting);pnlInputArea.setBounds(0, 279, 292, 67);JScrollPane jspInputArea = new JScrollPane(txtInputArea); pnlInputArea.add(jspInputArea);panel.add(pnlInputArea);pnlInputArea.setLayout(null);txtInputArea.setLineWrap(true);/pnlInputArea.setBounds(10, 10, 272, 47);jspInputArea.setBounds(10, 10, 272, 47);bnClose.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) /按下关闭按钮则直接退出聊天室exitSystem(););bnClose.setBounds(99, 356, 74, 23);panel.add(bnClose);bnSend.addActionListener(new SendActionListener(this);bnSend.setBounds(197, 356, 74, 23);bnSend.setMnemonic(0);panel.add(bnSend);this.setMinimumSize(minDimension);this.addWindowListener(new ClientFrameAction(this);/this.getRootPane().setDefaultButton(bnSend);public boolean login(String nickname)try dos.writeUTF(login_ + nickname);int loginResult = dis.readInt();if(loginResult = 1)System.out.println(登陆成功,欢迎进入聊天室!);return true;else if(loginResult = -1)System.out.println(登陆失败,没有以login_开头);return false;else if(loginResult = 2)System.out.println(登陆失败,用户昵称已经存在!);return false; catch (IOException e) e.printStackTrace();return false;private class SendActionListener implements ActionListenerprivate ClientFrame frClientFrame; public SendActionListener(ClientFrame frClientFrame)this.frClientFrame = frClientFrame;public void actionPerformed(ActionEvent e) String saying = frClientFrame.getTxtInputArea().getText();/System.out.println(saying); frClientFrame.getTxtInputArea().setText(null);try frClientFrame.getDos().writeUTF(saying);frClientFrame.getDos().flush(); catch (IOException e1) e1.printStackTrace();public void exitSystem()new ClientFrameAction(this).windowClosing(null);public void disconnect() try this.setConnected(false);dos.close();dis.close();s.close(); catch (IOException e3) e3.printStackTrace();public void receiveMessage()new Thread(new ThreadreceiveMessage(this).start();private class ThreadreceiveMessage implements Runnableprivate ClientFrame frClientFrame;public ThreadreceiveMessage(ClientFrame frClientFrame)this.frClientFrame = frClientFrame;String message = ;public void run() try while(isConnected()message = dis.readUTF();System.out.println(message);frClientFrame.txtChatArea.append(message + n);Thread.sleep(100); catch (IOException e) e.printStackTrace(); catch (InterruptedException e) Terrupted();package TCP_chat_room.gui;import javax.swing.JOptionPane;public class MessageBox public static void showWarningMessage (String message) /confirmdialog是可选是或否的对话框/JOptionPane.showConfirmDialog(null, message, 温馨提示, JOptionPane.WARNING_MESSAGE);JOptionPane.showMessageDialog(null, message, 温馨提示, JOptionPane.WARNING_MESSAGE);/JOptionPane.showMessageDialog(null, message);public static void showErrorMessage(String message)JOptionPane.showMessageDialog(null, message, 错误提示, JOptionPane.ERROR_MESSAGE);public static int showConfirmMessage(String message)return JOptionPane.showConfirmDialog(null, message, 温馨提示, JOptionPane.YES_NO_OPTION,JOptionPane.ERROR_MESSAGE);package TCP_chat_room.gui;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import .ServerSocket;import .Socket;import .SocketException;import java.util.Collection;import java.util.Collections;import java.util.Hashtable;import java.util.Iterator;import java.util.Map;public class Server public static final int CHAT_ROOM_PORT = 44444;private int port;private ServerSocket ss;private Socket socket;private DataInputStream dis;private DataOutputStream dos;private Map clients = Collections.synchronizedMap(new Hashtable();public Server(int port) throws IOException ss = new ServerSocket(port);public boolean containedInClients(String tempName) Collection names = clients.values();Iterator it = names.iterator();while (it.hasNext() String existedName = it.next();if (existedName = tempName) return true;return false;/ public void validataLogin() throws IOException/ public void start() throws IOException while (true) socket = ss.accept();new Thread(new ClientThread(socket).start();private class ClientThread implements Runnable private Socket client;public ClientThread(Socket client) this.client = client;public void run() try dis = new DataInputStream(client.getInputStream();dos = new DataOutputStream(client.getOutputStream(); catch (IOException e1) e1.printStackTrace();try / 处理用户的登录信息String loginMessage = dis.readUTF();String nickname = loginMessage.substring(6);if (loginMessage.startsWith(login_) boolean existed = containedInClients(nickname);if (existed) dos.writeInt(2); else / 用户昵称还不存在,故登陆成功dos.writeInt(1);clients.put(client, loginMessage);sendToAllMessage(nickname + 进入聊天室!);String message;try while (true) dis = new DataInputStream(client.getInputStream();dos = new DataOutputStream(client.getOutputStream(); message = dis.readUTF(); if(message != null) sendToAllMessage(nickname + 说: + message); / d
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 六盘水市农村信用社联合社秋季校园招聘笔试备考题库(浓缩500题)及答案详解(名校卷)
- 邯郸市农村信用社联合社秋季校园招聘笔试备考题库(浓缩500题)及完整答案详解
- 2026年荆门市农村信用社联合社秋季校园招聘笔试备考题库(浓缩500题)及答案详解1套
- 山东省农村信用社联合社秋季校园招聘笔试备考题库(浓缩500题)及参考答案详解1套
- 2026年杭州市农村信用社联合社秋季校园招聘笔试备考题库(浓缩500题)及参考答案详解1套
- 四平市农村信用社联合社秋季校园招聘笔试备考题库(浓缩500题)附答案详解(培优b卷)
- 鄂州市农村信用社联合社秋季校园招聘笔试备考题库(浓缩500题)有答案详解
- 2026年武威市农村信用社联合社秋季校园招聘笔试备考题库(浓缩500题)及答案详解(夺冠)
- 上海市农村信用社联合社秋季校园招聘笔试备考题库(浓缩500题)附答案详解(综合题)
- 唐山市农村信用社联合社秋季校园招聘笔试备考题库(浓缩500题)附答案详解(综合题)
- 互感现象及应用试卷
- 第二单元维护社会秩序 检测题(含答案)-2025-2026学年八年级上册道德与法治
- 2025年公安辅警笔试考试题库及答案
- HTTP协议课件教学课件
- 物业防寒防冻安全培训课件
- 2025道中华铸牢中华民族共同体意识知识竞赛试题(+答案)
- 【诗歌鉴赏】2026届高三9月名校模考试分类汇编四
- T-CCUA 048-2025 政务信息系统运行维护费用定额测算方法
- 人工智能+汽车技术与应用(高职汽车类专业通)教案 5.1.1 AI如何帮助诊断汽车故障
- 产教融合机制课题申报书
- 建筑工地环保及噪音控制施工方案
评论
0/150
提交评论