java网络编程练习

2019-03-08 09:44|来源: 网路

1、练习--TCP客户端并发登陆/*
客户端通过键盘录入用户名,服务端对这个用户名进行校验。
如果该用户存在,在服务端显示XXX,已登陆。并在客户端显示XXX,欢迎光临
如果该用户不存在,在服务端显示XXX,尝试登陆。并在客户端显示XXX,该用户不存在
最多就登陆三次。
*/

Java代码   收藏代码
  1. import java.io.*;  

  2. import java.net.*;  

  3. class  LoginClient  

  4. {  

  5.        public static void main(String[] args)  

  6.        {  

  7.                Socket s = new Socket("192.168.0.101",10009);  

  8.                BufferedReader bufr  

  9.                        new BufferedReader(new InputStreamReader(System.in)));  

  10.                PrintWriter out = new PrintWriter(s.getOutputStream(),true);  

  11.                BufferedReader bufin =  

  12.                        new BufferedReader(new InputStreamReader(s.getInputStream()));  

  13.                for(int x = 0;x<3;x++)  

  14.                {  

  15.                        String line = bufr.readLine();  

  16.                        if(line == null)  

  17.                                break;  

  18.                        out.println(line);  

  19.                        String info = bufin.readLine();  

  20.                        System.out.println("info")+info);  

  21.                        if(info.contains("欢迎"))  

  22.                                break;  

  23.  

  24.                }  

  25.        }  

  26. }  



Java代码   收藏代码
  1. class UserThread implements Runnable  

  2. {  

  3.        private Socket s ;  

  4.        UserThread(Socket s  

  5.        {  

  6.                this.s = s ;  

  7.        }  

  8.        public void run()  

  9.        {  

  10.                String ip = s.getInetAddress().getHostAddress();  

  11.                System.out.println(ip+"....connected");  

  12.                try  

  13.                {  

  14.                        for(int x= 0;x<3;x++)  

  15.                        {  

  16.                                BufferedReader bufin =  

  17.                                    new BufferedReader(new InputStreamReader(s.getInputStream()));  

  18.                                String name = bufin.readLine();  

  19.                                if(name==null)  

  20.                                        break;  

  21.                                BufferedReader bufr =          

  22.                                    new BUfferedReader(new FileReader("user.txt"));  

  23.                                PrintWriter out = new PrintWriter(s.getOutputStream());  

  24.                                String line = null;  

  25.                                boolean flag = false;  

  26.                                while((line = bufr.readLine())!=null)  

  27.                                {  

  28.                                        if(line.equals(name))  

  29.                                        {  

  30.                                                flag = true;  

  31.                                                break;  

  32.                                        }  

  33.                                }  

  34.                                if(flag)  

  35.                                {  

  36.                                        System.out.println(name+",已经登录");  

  37.                                        out.println(name+",欢迎光临");  

  38.                                        break;  

  39.                                }  

  40.                                else  

  41.                                {  

  42.                                        System.out.println(name+",尝试登陆");  

  43.                                        out.println(name+",该用户不存在");  

  44.                                }  

  45.                        }  

  46.                }  

  47.                catch(Exception e )  

  48.                {  

  49.                        throw new RuntimeException(ip+"校验失败");  

  50.                }  

  51.        }  

  52. }  



Java代码   收藏代码
  1. class LoginServer  

  2. {  

  3.        public static void main(String[] args)  

  4.        {  

  5.                ServerSocket ss = new ServerSocket(10009);  

  6.                while(true)  

  7.                {  

  8.                        Socket s = ss.accept();  

  9.                        new Thread(new UserThread(s)).start();  

  10.                }  

  11.        }  

  12. }  




练习:浏览器客户端,自定义服务器
客户端:浏览器
服务端:自定义

Java代码   收藏代码
  1. import java.io.*;  

  2. import java.net.*;  

  3. class ServerDemo  

  4. {  

  5.        public static void main(String[] args)  

  6.        {  

  7.                ServerSocket ss = new ServerSocket(10010);  

  8.                Socket s = ss.accept();  

  9.                System.out.println(s.getInetAddress().getHostAddress());  

  10.                PrintWriter out = new PrintWriter(s.getOutputStream(),true);  

  11.                out.println("客户端你好");  

  12.                s.close();  

  13.                ss.close();  

  14.        }  

  15. }  




在浏览器中输入:http://192.168.0.101:10010

telnet    windows 中的远程登陆命令,可以理解为客户端软件
在这里可以在命令提示行中:telnet  192.168.0.101 10010
这样就可以连接到我们自定义的服务器了。


练习:
客户端:浏览器
服务端:Tomcat服务器。
练习:
客户端:自定义
服务端:Tomcat服务器

Java代码   收藏代码
  1. import java.io.*;  

  2. import java.net.*;  

  3. class ServerDemo  

  4. {  

  5.        public static void main(String[] args)  

  6.        {  

  7.                ServerSocket ss = new ServerSocket(10010);  

  8.                Socket s = ss.accept();  

  9.                System.out.println(s.getInetAddress().getHostAddress());  

  10.  

  11.                InputStream in = s.getInputStream();  

  12.                byte[] buf = new byte[1024];  

  13.                int len = in.read(buf);  

  14.                System.out.println(len+"........"+new String(buf,0,len));  

  15.  

  16.                PrintWriter out = new PrintWriter(s.getOutputStream(),true);  

  17.                out.println("客户端你好");  

  18.                s.close();  

  19.                ss.close();  

  20.        }  

  21. }  



自定义的客户端
Java代码   收藏代码
  1. import java.io.*;  

  2. import java.net.*;  

  3. class MyIE  

  4. {  

  5.        public static void main(String[] args) throws Exception  

  6.        {  

  7.                Socket s = new Socket("192.168.0.101",8080);  

  8.                PrintWriter out = new PrintWriter(s.getOutputStream(),true);  

  9.                //GET  命令,表示访问GET后面的内容  

  10.                out.println("GET / myweb/demo.html HTTP/1.1");  

  11.                //  

  12.                out.println("Accept: */*");  

  13.                //所接受的语言  

  14.                out.println("Accept-Language:zh-cn");  

  15.                //访问的主机与端口号  

  16.                out.println("Host:192.168.0.101:10010");  

  17.                out.println("Connection:Keep-Alive");//注意该行下面要有两空行  

  18.                out.println();  

  19.                out.println();  

  20.                BufferedReader bufr =  

  21.                        new BufferedReader(new InputStreamReader(s.getInputStream()));  

  22.                String line = null;  

  23.                while((line = bufr.readLine())!=null)  

  24.                {  

  25.                        System.out.println(line);  

  26.                }  

  27.                s.close();  

  28.  

  29.        }  

  30. }  



练习:自定义界面浏览器
Java代码   收藏代码
  1. import java.io.*;  

  2. import java.net.*;  

  3. import java.awt.*;  

  4. import java.awt.event.*;  

  5. class MyIEByGUI  

  6. {  

  7.        private Frame f;  

  8.        private TextField tf;  

  9.        private Button but;  

  10.        private TextArea ta;  

  11.        private Dialog d;  

  12.        private Label lab;  

  13.        private Button okBut;  

  14.         MyIEByGUI ()  

  15.        {  

  16.                init();  

  17.        }  

  18.        public void init()  

  19.        {  

  20.                f = new Frame("my window");  

  21.                f.setBounds(300,100,600,500);  

  22.                f.setLayout(new FlowLayout());  

  23.                  

  24.                tf = new TextField(60);  

  25.                but = new Button("转到");  

  26.                ta = new TextArea(25,70);  

  27.                  

  28.                d = new Dialog(f,“提示信息-self",true);  

  29.                d.setBounds(400,200,240,150);  

  30.                d.setLayout(new FlowLayout());  

  31.                lab = new Label();  

  32.                okBut = new Button("确定");  

  33.                d.add(lab);  

  34.                d.add(okBut);  

  35.                f.add(tf);  

  36.                f.add(but);  

  37.                f.add(ta);  

  38.                myEvent();  

  39.                f.setVisible(true);  

  40.                  

  41.        }  

  42.        private void myEvent()  

  43.        {  

  44.                okBut.addActionListener(new ActionListener()  

  45.                {  

  46.                        public void actionPerformed(ActionEvent e)  

  47.                        {  

  48.                                d.setVisible(false);  

  49.                        }  

  50.                });  

  51.                d.addWindowListener(new WindowAdapter()  

  52.                {  

  53.                        public void windowClosing(WindowEvent e)  

  54.                        {  

  55.                                d.setVisible(false);  

  56.                        }  

  57.                });  

  58.                tf.addKeyListener(new KeyAdapter()  

  59.                {  

  60.                        public void keyPressed(KeyEvent e)  

  61.                        {  

  62.                                if(e.getKeyCode()==KeyEvent.VK_ENTER)  

  63.                                        showDir();  

  64.                        }  

  65.                });  

  66.                but.addActionListener(new ActionListener()  

  67.                {  

  68.                        public void actionPerformed(ActionEvent e)  

  69.                        {  

  70.                                showDir();  

  71.                        }  

  72.                });  

  73.                f.addWindowListener(new WindowAdapter()  

  74.                {  

  75.                        public void windowClosing(WindowEvent e)  

  76.                        {  

  77.                                System.exit(0);  

  78.                        }  

  79.                });  

  80.        }  

  81.        private void showDir()  

  82.        {  

  83.                ta.setText("");  

  84.                String url = tf.getText();//http://192.168.0.101:8080/myweb/demo.html  

  85.                 int index1 = url.indexOf("//")+2;    

  86.                int index2 = url.indexOf("/",index1);  

  87.                String str =url.substring(index1,index2);  

  88.                Stirng[] arr = str.split(":");  

  89.                String host = arr[0];  

  90.                String port = arr[1];  

  91.                String path = rul.substring(index2);  

  92.               // ta.setText(str+"    "+path);  

  93.                /*

  94.                String dirPath = tf.getText();

  95.                File dir = new File(dirPath);

  96.                if(dir.exists()&&dir.isDirectory())

  97.                {

  98.                        ta.setText("");

  99.                        String[] names = dir.list();

  100.                        for(String name:names)

  101.                        {

  102.                                ta.apend(name+"\r\n");

  103.                        }

  104.                }

  105.                else

  106.                {

  107.                        String info = "您输入的信息"+dirPath+"是错误的,请重新");

  108.                        lab.setText(info);

  109.                        d.setVisible(true);

  110.                }

  111.                */  

  112.      Socket s = new Socket(host,post);  

  113.                PrintWriter out = new PrintWriter(s.getOutputStream(),true);  

  114.                //GET  命令,表示访问GET后面的内容  

  115.                out.println("GET / myweb/demo.html HTTP/1.1");  

  116.                //  

  117.                out.println("Accept: */*");  

  118.                //所接受的语言  

  119.                out.println("Accept-Language:zh-cn");  

  120.                //访问的主机与端口号  

  121.                out.println("Host:"+host+":"+port);  

  122.                out.println("Connection:Keep-Alive");//注意该行下面要有两空行  

  123.                out.println();  

  124.                out.println();  

  125.                BufferedReader bufr =  

  126.                        new BufferedReader(new InputStreamReader(s.getInputStream()));  

  127.                String line = null;  

  128.                while((line = bufr.readLine())!=null)  

  129.                {  

  130.                        System.out.println(line);  

  131.                }  

  132.                s.close();  

  133.        }  

  134.        public static void main(String[] args) throws Exception  

  135.        {  

  136.                new MyIEByGUI();  

  137.        }  

  138. }  




2、URL:统一资源定位符
   构造方法:
           URL(String spec):根据String表示形式创建URL对象
           URL(String protocol,String host ,int port,String file):根据指定protocol(协议), host ,port和file创建URL对象

Java代码   收藏代码
  1. class URLDemo  

  2. {  

  3.        public static void main(String[] args) throws MalformedURLException  

  4.        {  

  5.                URL url = new URL("http://192.168.0.101:8080/meweb/demo.html?name=haha&age=39");  

  6.                sop(url.getProtocol());//协议名http  

  7.                sop(url.getHost());//主机名192.168.0.101  

  8.                sop(url.getPort());//端口号8080,没有指定端口时,返回-1(http://192.168.0.101/meweb/demo.html)  

  9.                sop(url.getPath());//路径meweb/demo.html  

  10.                sop(url.getFile());//文件名meweb/demo.html?name=haha&age=39  

  11.                sop(url.getQuery());//查询部name=haha&age=39  

  12.                //如果没有指定端口,则有如下代码,默认80  

  13.              //  int port = getPort();  

  14.             //   if(port==-1)  

  15.                 //   prot=80;  

  16.        }  

  17.        public static void sop(Object obj)  

  18.        {  

  19.                System.out.println(obj);  

  20.        }  

  21. }  


方法:public URLConnection openConnection() throws IOException
该方法返回一个URLConnection对象,它表示到URL所引用的远程对象的连接
类:public Abstract class URLConnection extends Object
该抽象类是所有类的超类,它代表应用程序和URL之间的通信链接,此类的实例可用于读取和写入此URL应用的资源。通常,创建一个到URL的连接需要几个步骤
       1、通过在URL上调用openConnection方法创建连接对象
       2、处理设置参数和一般请求属性
       3、使用connect方法建立到远程对象的实际链接
       4、远程对象变为可用,远程对象的头字段和内容变为可访问
Java代码   收藏代码
  1. import java.net.*;  

  2. import java.io.*;  

  3. class URLConnectionDemo  

  4. {  

  5.        public static void main(String[] args) throws Exception  

  6.        {  

  7.                /*

  8.                用Socket做的连接都是在传输层,而URL做的连接在应用层(没有响应头),

  9.                */  

  10.                URL url = new URL("http://192.168.0.101:8080/meweb/demo.html");  

  11.                URLConnection conn = url.openConnection();  

  12.                sop(conn);  

  13.  

  14.                InputStream in = conn.getInputStream();  

  15.                byte[] buf = new byte[1024];  

  16.                int len = in.read(buf);  

  17.                sop(new String(buf,0,len));  

  18.                  

  19.        }  

  20.        public static void sop(Object obj)  

  21.        {  

  22.                System.out.println(obj);  

  23.        }  

  24. }  

  25.  

  26.  

  27. 用URl方式替代socket,自定义浏览器重写;主要目的是去掉响应头  

  28. 响应头:  




Java代码   收藏代码
  1. /*

  2.                out.println("GET / myweb/demo.html HTTP/1.1");

  3.                //

  4.                out.println("Accept: */*");  

  5.                //所接受的语言  

  6.                out.println("Accept-Language:zh-cn");  

  7.                //访问的主机与端口号  

  8.                out.println("Host:192.168.0.101:10010");  

  9.                out.println("Connection:Keep-Alive");//注意该行下面要有两空行  

  10.              

  11.  

  12. */  



原理:服务端在返回给客户端的时候,内容包括响应头和数据内容,socket传输层接收响应头和数据,因此用socket做的浏览器会显示响应头;而URL是在应用层的,在传输层接收了响应头和数据,在应用层解析了响应头,因此显示出来的只有数据内容而没有响应头
Java代码   收藏代码
  1. import java.io.*;  

  2. import java.net.*;  

  3. import java.awt.*;  

  4. import java.awt.event.*;  

  5. class MyIEByGUI  

  6. {  

  7.        private Frame f;  

  8.        private TextField tf;  

  9.        private Button but;  

  10.        private TextArea ta;  

  11.        private Dialog d;  

  12.        private Label lab;  

  13.        private Button okBut;  

  14.         MyIEByGUI ()  

  15.        {  

  16.                init();  

  17.        }  

  18.        public void init()  

  19.        {  

  20.                f = new Frame("my window");  

  21.                f.setBounds(300,100,600,500);  

  22.                f.setLayout(new FlowLayout());  

  23.                  

  24.                tf = new TextField(60);  

  25.                but = new Button("转到");  

  26.                ta = new TextArea(25,70);  

  27.                  

  28.                d = new Dialog(f,“提示信息-self",true);  

  29.                d.setBounds(400,200,240,150);  

  30.                d.setLayout(new FlowLayout());  

  31.                lab = new Label();  

  32.                okBut = new Button("确定");  

  33.                d.add(lab);  

  34.                d.add(okBut);  

  35.                f.add(tf);  

  36.                f.add(but);  

  37.                f.add(ta);  

  38.                myEvent();  

  39.                f.setVisible(true);  

  40.                  

  41.        }  

  42.        private void myEvent()  

  43.        {  

  44.                okBut.addActionListener(new ActionListener()  

  45.                {  

  46.                        public void actionPerformed(ActionEvent e)  

  47.                        {  

  48.                                d.setVisible(false);  

  49.                        }  

  50.                });  

  51.                d.addWindowListener(new WindowAdapter()  

  52.                {  

  53.                        public void windowClosing(WindowEvent e)  

  54.                        {  

  55.                                d.setVisible(false);  

  56.                        }  

  57.                });  

  58.                tf.addKeyListener(new KeyAdapter()  

  59.                {  

  60.                        public void keyPressed(KeyEvent e)  

  61.                        {  

  62.                                if(e.getKeyCode()==KeyEvent.VK_ENTER)  

  63.                                        showDir();  

  64.                        }  

  65.                });  

  66.                but.addActionListener(new ActionListener()  

  67.                {  

  68.                        public void actionPerformed(ActionEvent e)  

  69.                        {  

  70.                                showDir();  

  71.                        }  

  72.                });  

  73.                f.addWindowListener(new WindowAdapter()  

  74.                {  

  75.                        public void windowClosing(WindowEvent e)  

  76.                        {  

  77.                                System.exit(0);  

  78.                        }  

  79.                });  

  80.        }  

  81.        private void showDir()  

  82.        {  

  83.                ta.setText("");  

  84.                String url = tf.getText();//http://192.168.0.101:8080/myweb/demo.html  

  85.                URL url = new URL(url);  

  86.                URLConnection conn = url.openConnection();  

  87.                sop(conn);  

  88.  

  89.                InputStream in = conn.getInputStream();  

  90.                byte[] buf = new byte[1024];  

  91.                int len = in.read(buf);  

  92.                ta.setText(new String(buf,0,len));  

  93.                  

  94.        }  

  95.        public static void main(String[] args) throws Exception  

  96.        {  

  97.                new MyIEByGUI();  

  98.        }  

  99. }  



3、类public abstract class SocketAddress extends Object implements Serializable
   此类 表示不带任何协议附件的Socket Address ,作为一个抽象类,应通过特定的、协议相关的实现为其创建子类,它提供不可变对象,供套接字用于绑定、连接或用作返回值。
   直接已知子类:InetSocketAddress

   public class InetSocketAddress extends SocketAddress
   此类实现IP套接字地址(IP地址+端口号).它还可以是一个对(主机名+端口号),在此情况下,将尝试解析主机名。如果解析失败,则该地址将被视为未解析地址,但是其在某些情形下仍然可以使用,比如通过代理连接。
   它提供不可变对象,供套接字用于绑定、连接或用作返回值
   通配符是一个特殊的本地IP地址,它通常表示”任何“,只能用于bind操作

4、类ServerSocket的构造方法
   ServerSocket(int port ,int backlog):port,端口号;backlog,表示队列的最大长度,也就是同时在线人数。比如,backlog是3,那么只能允许3个人同时连接,第四个就连接不上

5、域名解析:
   http://192.168.0.101:8080/myweb/demo.html
   想要将主机名翻译成IP地址,需要域名解析,DNS
   首先找域名解析服务器(该服务器上存储的都是,主机名与地址的映射关系,如 sina    19.19.19.19)
   根据域名获得IP地址,然后读取地址找到网站

注意:本机地址:http://127.0.0.1:8080    与http://localhost:8080   是对应的,其 对应关系在
       C:\Windows\System32\drivers\etc

其内容为:
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
# 127.0.0.1       localhost
# ::1             localhost

在这里可以修改localhost,例如myhost,那么以后就可以使用myhost了,修改后localhost就不能用了。

我们在访问主机的时候,先访问本地        C:\Windows\System32\drivers\etc  是否有该主机名,如果有就访问其对应的地址,如果没有就访问网上的网站。

如果我们在文件内配置上:13.12.11.10      www.sina.com.cn
我们再访问新浪的时候,会先找本地文件中查找,找到13.12.11.10,则直接找到网站,就不用再走DNS服务器了。

另一种用法;让付费软件更新失败
付费软件一般都是,在启动软件的时候,软件会自动连接网站提供一些信息,该信息就包括免费期信息,如果免费期到了,就需要付费了,这时我们可以不让该软件连接网站,就把该网站的域名对应本机地址,就是在该文件上设置:
如:127.0.0.1      www.myelipse.com      这样:启动软件,找到该文件,然后访问127.0.0.1就无法连接到其网站了


转自:http://hcy-520.iteye.com/blog/2233713


相关问答

更多
  • 买书,附光盘
  • 想学习编程的加:33402145 热烈欢迎重量级高手进入!!!
  • 看看文档就解决了 InputStream java.net.Socket.getInputStream() throws IOException Returns an input stream for this socket.If this socket has an associated channel then the resulting input stream delegates all of its operations to the channel. If the channel is in n ...
  • notify = new String(name+":"+ip).getBytes(); 这样写的话,notify必须是byte数组吧: String newstr =new String (notify); //假设newstr接收了notify,如果notify是字符串,直接赋值就行 String strs [] = newstr.split(":"); //以“:”为标志分组 String name = strs[0]; //因为newstr中只有一个“:”,所以第0个元素就是name String ...
  • java基础是必须要会的。 网络编程这部分其实没什么东西,对于线程和并发方面要求的高一些。 对于一些简单应用来说,如果基础好的话看两个星期的书,做点联系就可以了。JAVA给提供了一套API,针对于TCP和UDP协议来操作,另外有关IO方面要了解。 如果研究深了的话就复杂了。各种协议的实现、系统底层操作等等很复杂,我也说不太明白,一步步来吧。 JAVA语言程序设计这本书里有关于网络编程的知识,还有习题和例子,挺好。
  • Java网络编程的基础知识、 套接字编程、非阻塞通信、创建HTTP服务器与客户程序、数据报通信、对象的序列化与反序列化、Java反射机制、RMI框架、JDBCAPI、JavaMail API、MVC设计模式、安全网络通信、CORBA和Web服务。