当前位置:文档之家› 计算机网络原理实验报告

计算机网络原理实验报告

多线程Web服务器1实验目的:用JA V A语言开发一个多线程的WEB服务器,它能并行服务于多个请求。

发送网页文件,让网页文件能够通过在URL中制定端口号来被浏览器使用。

2实验代码及截图class ConnectionThread extends Thread {Socket client;int counter;public ConnectionThread(Socket cl,int c) {client = cl;counter = c;}public void run() // 线程体{try {String destIP=client.getInetAddress().toString(); // 客户机IP地址int destport=client.getPort(); // 客户机端口号System.out.println("Connection "+counter+":connected to "+destIP+" on port "+destport+".");PrintStream outstream=newPrintStream(client.getOutputStream());DataInputStream instream=newDataInputStream(client.getInputStream());String inline=instream.readLine(); // 读取Web浏览器提交的请求信息System.out.println("Received:"+inline);if (getrequest(inline)) { // 如果是GET请求String filename=getfilename(inline);File file=new File(filename);if (file.exists()) { // 若文件存在,则将文件送给Web 浏览器System.out.println(filename+" requested.");outstream.println("HTTP/1.0 200 OK");outstream.println("MIME_version:1.0");outstream.println("Content_Type:text/html");int len=(int)file.length();outstream.println("Content_Length:"+len);outstream.println("");sendfile(outstream,file); // 发送文件outstream.flush();} else { // 文件不存在时String notfound="<html><head><title>Not Found</title></head><body><h1>Error 404-file notfound</h1></body></html>";outstream.println("HTTP/1.0 404 no found");outstream.println("Content_Type:text/html");outstream.println("Content_Length:"+notfound.length()+2);outstream.println("");outstream.println(notfound);outstream.flush();}}long m1=1;while (m1<11100000){m1++;} // 延时client.close();} catch (IOException e) {System.out.println("Exception:"+e);}}/* 获取请求类型是否为“GET” */boolean getrequest(String s) {if (s.length()>0){if (s.substring(0,3).equalsIgnoreCase("GET"))return true;}return false;}/* 获取要访问的文件名 */String getfilename(String s) {String f=s.substring(s.indexOf(' ')+1);f=f.substring(0,f.indexOf(' '));try {if (f.charAt(0)=='/')f=f.substring(1);} catch (StringIndexOutOfBoundsException e) {System.out.println("Exception:"+e);}if (f.equals("")) f="index.html";return f;}/*把指定文件发送给Web浏览器 */void sendfile(PrintStream outs,File file) {try {DataInputStream in=new DataInputStream(new FileInputStream(file));int len=(int)file.length();byte buf[]=new byte[len];in.readFully(buf);outs.write(buf,0,len);outs.flush();in.close();} catch (Exception e) {System.out.println("Error retrieving file.");System.exit(1);}}}public class websever {public static void main(String[] args) {// TODO Auto-generated method stubint i=1, PORT=8081;ServerSocket server=null;Socket client=null;try {server=new ServerSocket(PORT);System.out.println("Web Server is listening on port "+server.getLocalPort());while(true){client=server.accept(); // 接受客户机的连接请求new ConnectionThread(client,i).start();i++;}} catch (Exception e) {System.out.println(e);}}}3实验软硬件环境eclipseWindows xpIE浏览器4实验步骤(1) 连接:Web浏览器与Web服务器建立连接,打开一个称为socket(套接字)的虚拟文件,此文件的建立标志着连接建立成功。

(2) 请求:Web浏览器通过socket向Web服务器提交请求。

HTTP的请求一般是GET或POST命令(POST用于FORM参数的传递)。

GET命令的格式为:GET 路径/文件名 HTTP/1.1文件名指出所访问的文件,HTTP/1.1指出Web浏览器使用的HTTP版本。

(3) 应答:Web浏览器提交请求后,通过HTTP协议传送给Web服务器。

Web服务器接到后,进行事务处理,处理结果又通过HTTP传回给Web浏览器,从而在Web浏览器上显示出所请求的页面。

为了告知 Web浏览器传送内容的类型,Web服务器首先传送一些HTTP头信息,然后传送具体内容(即HTTP体信息),HTTP头信息和HTTP体信息之间用一个空行分开。

(4) 关闭连接:当应答结束后,Web浏览器与Web服务器必须断开,以保证其它Web浏览器能够与Web服务器建立连接。

5实验心得Java中实现多线程有两种途径:继承Thread类或者实现Runnable接口。

此处使用了接口的方式生成线程,因为接口可以实现多继承,况且Runnable只有一个run方法,很适合继承。

在使用Thread的时候只需继承Thread,并且new一个实例出来,调用start()方法即可以启动一个线程。

在本次试验中,通过用java语言开发一个多线程的web服务器,能并行服务于多个请求,来掌握套接字编程技术,了解并运用http协议的作用原理,实现多线程web服务器设计。

6参考文献:,1计算机网络:自顶向下方法(原书第4版)/(美)库罗斯(Kurose,J.F.)等著;陈鸣译--北京:机械工业出版社,2008.122java从入门到精通:李钟尉,马文强,陈丹丹等编著;-- 清华大学出版社,2008.93实验指导书邮件客户机1实验目的:为发送者提供一个图形界面,其中包含:发送电子邮件地址、接受者电子邮件地址、邮件主题和本身。

开发一个Internet上的使用STMP协议的网络服务器的邮件客户端,在Windows XP,Windows7系统下,使用JA V A语言开发,并最终运行该程序。

2实验部分代码及截图:在发件人框中填写相应的信息,点击发送按钮即可向目标邮箱发送邮件。

public class MailMessage {public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {public void run() {try {SendFrame frame = new SendFrame();frame.setVisible(true);} catch (Exception e) {e.printStackTrace();}/*** Create the frame.*/public SendFrame() {thisFrame=this;setTitle("Java Mailclient");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(100, 100, 450, 328);contentPane = new JPanel();contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));setContentPane(contentPane);contentPane.setLayout(null);JLabel lblFrom = new JLabel("from:");lblFrom.setBounds(10, 10, 54, 22);contentPane.add(lblFrom);JLabel lblTo = new JLabel("To:");lblTo.setBounds(10, 42, 42, 22);contentPane.add(lblTo);JLabel lblSubject = new JLabel("Subject:"); lblSubject.setBounds(10, 74, 54, 22); contentPane.add(lblSubject);txt_From = new JTextField();txt_From.setEditable(false);txt_From.setText("1025674623@");txt_From.setBounds(49, 11, 383, 21); contentPane.add(txt_From);txt_From.setColumns(10);txt_To = new JTextField();txt_To.setText("1025674623@");txt_To.setColumns(10);txt_To.setBounds(49, 42, 383, 21); contentPane.add(txt_To);text_Subject = new JTextField();text_Subject.setText("作业2:邮件客户机"); text_Subject.setColumns(10);text_Subject.setBounds(66, 73, 366, 21); contentPane.add(text_Subject);JLabel lblMassage = new JLabel("Massage:"); lblMassage.setBounds(10, 101, 64, 15); contentPane.add(lblMassage);JButton btnQuit = new JButton("Quit"); btnQuit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { thisFrame.dispose();}});btnQuit.setBounds(295, 271, 137, 23); contentPane.add(btnQuit);JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(10, 229, 422, -101); contentPane.add(scrollPane);Panel panel = new Panel();panel.setBounds(10, 115, 422, 156);contentPane.add(panel);panel.setLayout(null);ScrollPane scrollPane_1 = new ScrollPane();scrollPane_1.setBounds(0, 0, 422, 156);panel.add(scrollPane_1);final TextArea Send_TextArea = new TextArea();Send_TextArea.setText("你好!这是一封测试邮件");Send_TextArea.setBounds(0, 0, 440, 170);scrollPane_1.add(Send_TextArea);JButton btnSend = new JButton("Send");btnSend.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String txtfrom=txt_From.getText();String txtto=txt_To.getText();String txtsubject=text_Subject.getText();String sendtextarea=Send_TextArea.getText();try {MailMessage message=new MailMessage();message.setFrom(txtfrom);//发件人message.setTo( txtto);//收件人String server="";//邮件服务器message.setSubject(txtsubject);//邮件主题message.setContent(sendtextarea);//邮件内容message.setDatafrom(txtfrom);//发件人,在邮件的发件人栏目中显示message.setDatato(txtto);//收件人,在邮件的收件人栏目中显示message.setUser("1025674623");//登陆邮箱的用户名message.setPassword("zjr*******(保密)");//登陆邮箱的密码SendFrame smtp=new SendFrame(server,25);boolean flag;flag=smtp.sendMail(message,server);if(flag){JOptionPane.showMessageDialog(null, "信息已成功发送!", "提示", RMATION_MESSAGE);}else{JOptionPane.showMessageDialog(null, "邮件发送失败!", "提示", RMATION_MESSAGE);}//System.out.println("iuhfihulaeih ba ");} catch (UnknownHostException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}// JOptionPane.showMessageDialog(null, "信息已成功发送!", "提示", RMA TION_MESSAGE);// System.out.println(txtfrom+"\n"+txtto+"\n"+txtsubject+"\n"+sendtextarea);}});btnSend.setBounds(10, 271, 144, 23);contentPane.add(btnSend);JButton btnClear = new JButton("Clear");btnClear.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {txt_To.setText("");text_Subject.setText("");Send_TextArea.setText("");JOptionPane.showMessageDialog(null, "信息删除成功!", "提示", RMA TION_MESSAGE);}});btnClear.setBounds(149, 271, 150, 23);contentPane.add(btnClear);}private boolean debug=true;BASE64Encoder encode=new BASE64Encoder();//用于加密后发送用户名和密码private Socket socket;public SendFrame(String server,int port) throws UnknownHostException, IOException{try{socket=new Socket(server,25);}catch(SocketException e){// System.out.println(e.getMessage());}catch(Exception e){e.printStackTrace();}finally{// System.out.println("已经建立连接!");}}//注册到邮件服务器public void helo(String server,BufferedReader in,BufferedWriter out) throws IOException{ int result;result=getResult(in);//连接上邮件服务后,服务器给出220应答if(result!=220){throw new IOException("连接服务器失败");}result=sendServer("HELO "+server,in,out);//HELO命令成功后返回250if(result!=250){throw new IOException("注册邮件服务器失败!");}}private int sendServer(String str,BufferedReader in,BufferedWriter out) throws IOException{out.write(str);out.newLine();out.flush();if(debug){// System.out.println("已发送命令:"+str);}return getResult(in);}public int getResult(BufferedReader in){String line="";try{line=in.readLine();if(debug){// System.out.println("服务器返回状态:"+line);}}catch(Exception e){e.printStackTrace();}//从服务器返回消息中读出状态码,将其转换成整数返回StringTokenizer st=new StringTokenizer(line," ");return Integer.parseInt(st.nextToken());}public void authLogin(MailMessage message,BufferedReader in,BufferedWriter out) throws IOException{int result;result=sendServer("AUTH LOGIN",in,out);if(result!=334){throw new IOException("用户验证失败!");}result=sendServer(encode.encode(message.getUser().getBytes()),in,out);if(result!=334){throw new IOException("用户名错误!");}result=sendServer(encode.encode(message.getPassword().getBytes()),in,out);if(result!=235){throw new IOException("验证失败!");}}//开始发送消息,邮件源地址public void mailfrom(String source,BufferedReader in,BufferedWriter out) throws IOException{int result;result=sendServer("MAIL FROM:<"+source+">",in,out);if(result!=250){throw new IOException("指定源地址错误");}}// 设置邮件收件人public void rcpt(String touchman,BufferedReader in,BufferedWriter out) throws IOException{int result;result=sendServer("RCPT TO:<"+touchman+">",in,out);if(result!=250){throw new IOException("指定目的地址错误!");}}//邮件体//退出public void quit(BufferedReader in,BufferedWriter out) throws IOException{int result;result=sendServer("QUIT",in,out);}//发送邮件主程序public boolean sendMail(MailMessage message,String server){try{BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));BufferedWriter out=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));helo(server,in,out);//HELO命令authLogin(message,in,out);//AUTH LOGIN命令mailfrom(message.getFrom(),in,out);//MAIL FROMrcpt(message.getTo(),in,out);//RCPTdata(message.getDatafrom(),message.getDatato(),message.getSubject(),message.getContent(),in,o ut);//DATAquit(in,out);//QUIT}catch(Exception e){e.printStackTrace();return false;}return true;}}程序实现与服务器之间建立连接,根据服务器端发送的响应来完成建立连接的过程,然后根据服务器发送回的响应信息,根据相应的模式,发送相应的信息,从而建立起与邮件服务器端的连接以发送邮件。

相关主题