实验5-socket网络编程_第1页
实验5-socket网络编程_第2页
实验5-socket网络编程_第3页
实验5-socket网络编程_第4页
实验5-socket网络编程_第5页
已阅读5页,还剩22页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

深 圳 大 学 实 验 报 告 课程名称: 计算机网络 实验项目名称: Socket网络编程 学院:计算机与软件学院 专业: 物联网工程 指导教师: 崔来中 报告人:陈秋明 学号:2014150320 班级: 实验时间: 2016.04.20 实验报告提交时间: 2016.04.29 教务处制实验目的学习网络编程基本概念、InetAddress的应用、URL的应用、URLConnection的应用 。掌握Socket的TCP通信、 Socket的UDP通信掌握通过TCP实现网络文件传输的方法,掌握TCP连接是基于字符流实验环境使用Windows操作系统;Internet连接Eclipse+Java开发环境实验内容:5-1使用InetAddress类的方法获取本地机的名称和IP地址。使用InetAddress类的方法获取网站的IP地址,如果存在多个IP地址,要求全部返回。使用URL类下载深圳大学首页,并统计下载得到网页文件的大小5-2利用Socket类和ServerSocket类,编写一个C/S程序,实现聊天功能。5-3利用Socket类和ServerSocket类,编写一个C/S程序,实现网络文件传输。实验步骤:(用文字描述实验过程,可用截图辅助说明)5-1(1) 使用InetAddress类的方法获取本地机的名称和IP地址。package socket;import .*;public class one public static void main(String args)tryInetAddress add=InetAddress.getLocalHost();System.out.println(add);catch(UnknownHostException e)System.out.println(error);(2) 使用InetAddress类的方法获取网站的IP地址,如果存在多个IP地址,要求全部返回。 package socket;import .*;public class one public static void main(String args)tryInetAddress add=InetAddress.getByName();System.out.println(add);catch(UnknownHostException e)System.out.println(error);(3)使用URL类下载深圳大学首页,并统计下载得到网页文件的大小package socket;import .*;import java.io.*;public class onepublic static void main(String aregs )throws ExceptionURL url=new URL();URLConnection uc=url.openConnection(); int size=uc.getContentLength();InputStream in=url.openStream();FileOutputStream fout=new FileOutputStream(new File(qwe.html);int a=0;while(a-1)a=in.read();fout.write(a);fout.close();System.out.println(文件大小:+size+B); 5-2(1) 编写完整程序;一个服务器端程序,一个客户端程序。服务器端和客户端都需要打印出接受到的消息和发出的命令客户端package udp;import .*;import java.io.*;public class Client public static void main(String args)String s=null;String t=time;String q=exit;Socket mysocket;DataInputStream in=null;DataOutputStream out=null;trymysocket=new Socket(localhost,4331);in=new DataInputStream(mysocket.getInputStream();out=new DataOutputStream(mysocket.getOutputStream();System.out.println(服务器启动完毕);System.out.println(创建客户连接); out.writeBytes(t);s=in.readUTF();System.out.println(s);Thread.sleep(500);out.writeBytes(q);s=in.readUTF();System.out.println(s);Thread.sleep(500);catch(IOException e)System.out.println(无法连接);catch(InterruptedException e)服务端package udp;import .*;import java.io.*;import java.util.*;import java.text.*;public class SS public static void main(String args)ServerSocket s=null;Socket fuck=null;DataInputStream in=null;DataOutputStream out=null;System.out.println(服务器启动完毕);trys=new ServerSocket(4331);catch(IOException e)System.out.println(error+e);System.out.println(创建客户连接);tryfuck=s.accept();in=new DataInputStream(fuck.getInputStream();out=new DataOutputStream(fuck.getOutputStream();String ddate=new SimpleDateFormat(yyyy-MM-dd HH:mm:ss).format(Calendar.getInstance().getTime();out.writeUTF(服务器当前时间为:+ddate);Thread.sleep(500);String g=Bye;out.writeUTF(g);catch(IOException e)System.out.println(无法连接);catch(InterruptedException e)()(2) 聊天室package socket;import java.awt.*;import java.awt.event.*;import javax.swing.*;import .*;import java.io.*;import java.util.*;public class Chatroom extends JFrame implements ActionListener, Runnable,KeyListenerImage Image;private TextArea ta;private JTextField ip;private JTextField port;private JButton ss_server;private JButton ss_client;private JTextField send_text;private JTextField name;private JButton ss_send;private JButton ss_exit;private JButton ss_clear;private Socket skt; public void keyReleased(KeyEvent f) public void keyPressed(KeyEvent f) if(f.getKeyCode()= KeyEvent.VK_ENTER) tryPrintWriter pw = new PrintWriter(skt.getOutputStream();String s1=name.getText();String s = send_text.getText();if(s=null) return;Calendar ca= new GregorianCalendar(); int hh = ca.get(Calendar.HOUR_OF_DAY); int mm = ca.get(Calendar.MINUTE); int ss = ca.get(Calendar.SECOND); String time = new String(hh + : + mm + : + ss + ); ta.append(time+s1+说:+n+s+n); String s3=time+s1+说:+n+s;pw.println(s3);pw.flush();send_text.setText();catch(Exception e)ta.append(发送失败!n);public void keyTyped(KeyEvent f)public void run()tryBufferedReader br = new BufferedReader(new InputStreamReader(skt.getInputStream();while(true)String s = br.readLine();if(s=null) break;ta.append(s + n);catch(Exception e)e.printStackTrace();public void actionPerformed(ActionEvent e)if(e.getSource()=ss_server)doServer();if(e.getSource()=ss_client)doClient();if(e.getSource()=ss_send)doSend();if(e.getSource()=ss_exit)doexit();if(e.getSource()=ss_clear)doclear();public void doServer()tryServerSocket server = new ServerSocket(Integer.parseInt(port.getText();skt = server.accept();ta.append(连接服务器成功!n);new Thread(this).start();catch(Exception e)ta.append(服务器启动失败!n);public void doClient()tryskt = new Socket(ip.getText(), Integer.parseInt(port.getText();ta.append(连接服务器成功!n);new Thread(this).start();catch(Exception e)ta.append(连接失败!n);public void doSend()tryPrintWriter pw = new PrintWriter(skt.getOutputStream();String s1=name.getText();String s = send_text.getText();if(s=null) return;Calendar ca= new GregorianCalendar(); int hh = ca.get(Calendar.HOUR_OF_DAY); int mm = ca.get(Calendar.MINUTE); int ss = ca.get(Calendar.SECOND); String time = new String(hh + : + mm + : + ss + ); ta.append(time+s1+说:+n+s+n); String s3=time+s1+说:+n+s;pw.println(s3);pw.flush();send_text.setText();catch(Exception e)ta.append(发送失败!n);public void doclear()ta.setText();public void doexit()System.exit(0);public Chatroom()Panel a1 = new Panel(); Panel a2 = new Panel(); Panel a3 = new Panel();this.setTitle(聊天室);this.setBounds(200,200,600,500);Container cc = this.getContentPane();JPanel p1 = new JPanel();cc.add(p1, BorderLayout.NORTH);p1.setBackground(new Color(200,200,250);ta = new TextArea();cc.add(ta, BorderLayout.CENTER);JPanel p2 = new JPanel();cc.add(p2, BorderLayout.SOUTH);p2.setBackground(new Color(250,150,200);ta.setForeground(new Color(0,0,250);JLabel p3 = new JLabel(new ImageIcon(2010.jpg);cc.add(p3, BorderLayout.EAST);p1.add(new JLabel(昵称:);name=new JTextField(,6);p1.add(name); name.setFont(new Font(宋体,Font.BOLD,14);p1.add(new JLabel(IP: );ip = new JTextField(, 15);p1.add(ip);p1.add(new JLabel(Port: );port = new JTextField(7777, 4);p1.add(port);ss_server = new JButton(侦听);ss_server.setForeground(new Color(150,100,250);ss_server.setFont(new Font(宋体,Font.BOLD,14);p1.add(ss_server);ss_client = new JButton(连接);ss_client.setForeground(new Color(150,100,250);ss_client.setFont(new Font(宋体,Font.BOLD,14);p1.add(ss_client);ss_clear = new JButton(清除);ss_clear.setForeground(new Color(150,100,250);ss_clear.setFont(new Font(宋体,Font.BOLD,14);p1.add(ss_clear);ss_exit = new JButton(退出);ss_exit.setForeground(new Color(150,100,250);ss_exit.setFont(new Font(宋体,Font.BOLD,14);p1.add(ss_exit); p2.setLayout(new BorderLayout();p2.add(new JLabel(发送消息:),BorderLayout.WEST);p2.setBackground(new Color(200,200,250);send_text = new JTextField(在?);p2.add(send_text, BorderLayout.CENTER);ss_send = new JButton(发送);p2.add(ss_send, BorderLayout.EAST);ss_clear.addActionListener(this);ss_exit.addActionListener(this); send_text.addKeyListener(this);ss_server.addActionListener(this);ss_client.addActionListener(this);ss_send.addActionListener(this);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);public static void main(String args)new Chatroom().setVisible(true);清除聊天信息退出聊天作为对比,左边聊天已退出5-3 利用Socket类和ServerSocket类,编写一个C/S程序,实现网络文件传输。服务端package socket;import java.io.BufferedInputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import .ServerSocket;import .Socket;public class Newserver int port = 8821; void start() Socket s = null; try ServerSocket ss = new ServerSocket(port); / 选择进行传输的文件 String filePath = D:test.txt; File fi = new File(filePath); / public Socket accept() throws / IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。 s = ss.accept(); System.out.println(服务端运行开始okokok!); System.out.println(服务器的线程1启动,与客户端1连接成功); DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream(); dis.readByte(); DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath); DataOutputStream ps = new DataOutputStream(s.getOutputStream(); System.out.println(要传输的文件为:+filePath); System.out.println(开始传输文件); /将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。 ps.writeUTF(fi.getPath()+fi.getName(); ps.flush(); ps.writeLong(long) fi.length(); ps.flush(); int bufferSize = 8192; byte buf = new bytebufferSize; while (true) int read = 0; if (fis != null) read = fis.read(buf); if (read = -1) break; ps.write(buf, 0, read); ps.flush(); / 注意关闭socket链接哦,不然客户端会等待server的数据过来, / 直到socket超时,导致数据不完整。 fis.close(); s.close(); ss.close(); System.out.println(文件传输完成); catch (Exception e) e.printStackTrace(); public static void main(String arg) new Newserver().start(); 客户端package fasf;import java.io.BufferedOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileOutputStream;public class Newclient private ClientSocket cs = null; private String ip = localhost;/ 设置成服务器IP private int port = 8821; private String sendMessage = Windwos; public Newclient() try if (createConnection() sendMessage(); getMessage(); catch (Exception ex) ex.printStackTrace(); private boolean createConnection() cs = new ClientSocket(ip, port); try cs.CreateConnection(); System.out.print(与服务器连接成功! + n); return true; catch (Exception e) System.out.print(与服务器连接失败! + n); return false; private void sendMessage() if (cs = null) return; try cs.sendMessage(sendMessage); catch (Exception e) System.out.print(发送消息失败! + n); private void getMessage() if (cs = null) return; DataInputStream inputStream = null; try inputStream = cs.getMessageStream(); catch (Exception e) System.out.print(接收消息缓存错误n); return; try /本地保存路径,文件名会自动从服务器端继承而来。 String savePath ; int bufferSize = 8192; byte buf = new bytebufferSize; int passedlen = 0; long len=0; savePath = inputStream.readUTF(); DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath); len = inputStream.readLong(); while (true) int read = 0; if (inputStream != null) read = inputStream.read(buf); passedlen += read; if (read = -1) break; System.out.println(接收到的文件为: + savePath + n); System.out.println(保存为: + savePath + n); fileOut.close(); catch (Exception e) System.out.println(接收消息错误 + n); return; public static void main(String arg) new Newclient(); 辅助类package fasf;import .*;import java.io.*;public class ClientSocket private String ip; private int port; private Socket socket = null; DataOutputStream out = null; DataInputStream getMessageStream = null; public ClientSocket(String ip, int port) this.ip = ip; this.port = port; /* * 创建socket连接 * * throws Exception * exception */ public void CreateConnection() throws Exception try socket = new Socket(ip, port); catch (Exception e) e.printStackTrace(); if (socket != null) socket.close(); throw e; finally public void sendMessage(String sendMessage) throws Exception try out = new DataOutputStream(socket.getOutputStream(); if (sendMessage.equals(Windows) out.writeByte(0x1); out.flush(); return; if (sendMessage.equals(Unix) out.writeByte(0x2); out.flush(); return; if (sendMessage.equals(Linux) out.writeByte(0x3); out.flush(); else out.writeUTF(sendMessage); out.flush(); catch (Exception e) e.printStackTrace(); if (out != null) out.close(); throw e; finally public DataInputStream getMessageStream() throws Exception try getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream(); return getMessageStream; catch (Exception e) e.printStackTrace(); if (getMessageStream != null) getMessageStream.close(); throw e; finally public void shutDownConnection() try if (out != null) out.close(); if (getMessageStream != null) getMessageStream.close(); if (socket != null) socket.close(); catch (Exception e) 实验结果:(此页附完成的实验结果、并给出个人对结果的分析、结论)实验过程与截图即实验结果。实验小结:(实验中出现问题的解决方法,实验心得体会等)该次实验虽然耗时较长,但难度不大。能很好的巩固上学期所学的Java编程。对Socket网络编程又有了进一步的了解。本以为计算机网络是一门理论课,没想到还有代码实践,两者可谓相辅相成,互为补充。计算机网络果然是一门极具实践意义的课程。指导教师批阅意见:成绩评定: 指导教师签字: 年 月 日备注:幸福,不能用手去捉摸,只能用心去琢磨,只能静静去体味。细细地品味了,你就享受到了它温馨的暖,或浓或淡的甜!幸福,其实很简单。幸福就是和爱人一起漫步,幸福就是吃到妈妈的拿手饭菜,幸福就是孩子在你的脚跟前转悠,幸福就是你能帮父母洗衣洗碗。幸福,其实很简单。拥有一份称心的工作,就是一种幸福;拥有一个温馨的家,就是一种幸福;拥有一位知心的朋友,就是一种幸福;拥有一份好的心态,就是一种幸福;拥有一个相濡以沫的爱人,那更是一种幸福。幸福就是如此的平平凡凡,幸福就是这样的简简单单。幸福,其实就是自己心灵的感觉,沉淀在自己的心底,看不见摸不着,没有那么直观,可那种体验与享受却

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论