一、网络编程(TCP-上传图片)
-
-
-
-
-
-
-
-
-
-
-
-
- import java.net.*;
- import java.io.*;
- class PicClient
- {
- public static void main(String[] args)throws Exception
- {
- Socket s=new Socket("172.16.56.237",1005);
- FileInputStream fis=new FileInputStream("e:\\1.jpg");
-
- OutputStream out=s.getOutputStream();
-
- byte[] buf=new byte[1024];
- int len=0;
-
- while((len=fis.read(buf))!=-1)
- {
- out.write(buf,0,len);
- }
-
- s.shutdownOutput();
-
- InputStream in=s.getInputStream();
- byte[] bufIn=new byte[1024];
-
- int num=in.read(bufIn);
- System.out.println(new String(bufIn,0,num));
-
- fis.close();
- s.close();
- }
- }
-
-
-
- import java.net.*;
- import java.io.*;
- class PicServer
- {
- public static void main(String[] args)throws Exception
- {
- ServerSocket ss=new ServerSocket(1005);
- Socket s=ss.accept();
-
- InputStream in=s.getInputStream();
-
- FileOutputStream fos=new FileOutputStream("f:\\server.jpg");
-
- byte[] buf=new byte[1024];
- int len=0;
- while((len=in.read(buf))!=-1)
- {
- fos.write(buf,0,len);
- }
-
- OutputStream out=s.getOutputStream();
- out.write("图片已收到".getBytes());
-
- fos.close();
- s.close();
- ss.close();
- }
- }
二、网络编程(TCP-客户端并发上传图片)
-
-
-
-
-
-
-
-
-
-
-
-
- import java.net.*;
- import java.io.*;
- class PicClient
- {
- public static void main(String[] args)throws Exception
- {
- if(args.length!=1)
- {
- System.out.println("请选择一个jpg格式的图片。");
- return;
- }
-
- File file=new File(args[0]);
- if(!(file.exists()&&file.isFile()))
- {
- System.out.println("该文件有问题,要么存在,要么不是文件");
- return;
- }
- if(!file.getName().endsWith(".jpg"))
- {
- System.out.println("图片格式错误,请重新选择");
- return;
- }
- if(file.length()>1024*1024*5)
- {
- System.out.println("文件过大,禁止上传!");
- return;
- }
-
-
- Socket s=new Socket("172.16.56.237",1005);
- FileInputStream fis=new FileInputStream(file);
-
- OutputStream out=s.getOutputStream();
-
- byte[] buf=new byte[1024];
- int len=0;
-
- while((len=fis.read(buf))!=-1)
- {
- out.write(buf,0,len);
- }
-
- s.shutdownOutput();
-
- InputStream in=s.getInputStream();
- byte[] bufIn=new byte[1024];
-
- int num=in.read(bufIn);
- System.out.println(new String(bufIn,0,num));
-
- fis.close();
- s.close();
- }
- }
-
-
-
-
-
-
-
-
-
-
-
-
- import java.net.*;
- import java.io.*;
- class PicThread implements Runnable
- {
- private Socket s;
- PicThread(Socket s)
- {
- this.s=s;
- }
- public void run()
- {
- int count=1;
-
- String ip=s.getInetAddress().getHostAddress();
- try
- {
-
- System.out.println(ip+"..........connceted");
-
- InputStream in=s.getInputStream();
-
-
-
- File file=new File("f:\\"+ip+"("+(count)+")"+".jpg");
- while(file.exists())
- file=new File("f:\\"+ip+"("+(count++)+")"+".jpg");
-
-
-
- FileOutputStream fos=new FileOutputStream(file);
-
- byte[] buf=new byte[1024];
- int len=0;
- while((len=in.read(buf))!=-1)
- {
- fos.write(buf,0,len);
- }
-
- OutputStream out=s.getOutputStream();
- out.write("图片已收到".getBytes());
-
- fos.close();
- s.close();
-
- }
- catch (Exception e)
- {
- throw new RuntimeException(ip+"上传失败!");
- }
- }
- }
- class PicServer
- {
- public static void main(String[] args)throws Exception
- {
- ServerSocket ss=new ServerSocket(1005);
-
- while(true)
- {
- Socket s=ss.accept();
- new Thread(new PicThread(s)).start();
- }
-
- }
- }
三、网络编程(TCP-客户端并发登录)
-
-
-
-
-
-
-
- import java.io.*;
- import java.net.*;
-
- class LoginClient
- {
- public static void main(String[] args)throws Exception
- {
- Socket s=new Socket("172.16.56.237",1005);
-
- BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
-
- PrintWriter out=new PrintWriter(s.getOutputStream(),true);
-
- BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
-
- for(int i=0;i<3;i++)
- {
- String line=bufr.readLine();
- if(line==null)
- break;
- out.println(line);
-
- String info=bufIn.readLine();
- System.out.println("info:"+info);
- if(info.contains("欢迎"))
- break;
- }
-
- bufr.close();
- s.close();
- }
- }
-
-
-
- import java.io.*;
- import java.net.*;
- class UserThread implements Runnable
- {
- private Socket s;
- UserThread(Socket s)
- {
- this.s=s;
- }
- public void run()
- {
- String ip=s.getInetAddress().getHostAddress();
- try
- {
- for(int i=0;i<3;i++)
- {
- BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
- String name=bufIn.readLine();
- if(name==null)
- return;
- BufferedReader bufr=new BufferedReader(new FileReader("e:\\user.txt"));
-
- PrintWriter out=new PrintWriter(s.getOutputStream(),true);
-
- String line=null;
-
- boolean flag=false;
- while((line=bufr.readLine())!=null)
- {
- if(line.equals(name))
- {
- flag=true;
- break;
- }
- }
- if(flag)
- {
- System.out.println(name+",已登录");
- out.println(name+",欢迎光临。");
- }
- else
- {
- System.out.println(name+",尝试登录。");
- out.println(name+",用户名不存在。");
- }
- }
-
- s.close();
- }
- catch (Exception e)
- {
- throw new RuntimeException(ip+"校验失败");
- }
- }
- }
-
- class LoginServer
- {
- public static void main(String[] args)throws Exception
- {
- ServerSocket ss=new ServerSocket(1005);
-
- while(true)
- {
- Socket s=ss.accept();
-
- new Thread(new UserThread(s)).start();
- }
- }
- }
四、网络编程(浏览器客户端-自定义服务端)
-
-
-
-
-
-
-
-
- import java.net.*;
- import java.io.*;
- class ServerDemo
- {
- public static void main(String[] args)throws Exception
- {
- ServerSocket ss=new ServerSocket(1005);
- Socket s=ss.accept();
-
- System.out.println(s.getInetAddress().getHostAddress());
-
- PrintWriter out=new PrintWriter(s.getOutputStream(),true);
-
- out.println("客户端你好");
-
- s.close();
-
- ss.close();
- }
- }
五、网络编程(浏览器客户端-Tomcat服务端)
1.下载好Tomcat服务端,解压到任意路径。
2.进入Tomcat文件夹的bin目录下,点击startup.bat文件,启动Tomcat服务器。
可以看到配置信息里面的服务器端口:8080
3.进入浏览器输入: http://172.16.56.237:8080/ 打开了Tomcat网页。
这样的话,自己写个HMTL:
- <html>
- <body>
- <h1>
- 这是我的第一个网页
- <h1>
- <font size=5 color=red>欢迎光临font>
- <div>
- 1234567890br>
- 3456789090br>
- 5678987654br>
- div>
- body>
- html>
保存成index.html文件。然后在Tomcat文件夹的webapps下建立一个myweb文件夹,将index.html放入。
在浏览器中指定具体服务器要打开html文件的路径:
http://172.16.56.237:8080//myweb/index.html
六、网络编程(自定义浏览器-Tomcat服务端)
-
-
-
-
-
- import java.net.*;
- import java.io.*;
- class ServerDemo
- {
- public static void main(String[] args)throws Exception
- {
- ServerSocket ss=new ServerSocket(1005);
- Socket s=ss.accept();
-
- System.out.println(s.getInetAddress().getHostAddress());
-
- InputStream in=s.getInputStream();
- byte[] buf=new byte[1024];
- int len=in.read(buf);
-
- System.out.println(new String(buf,0,len));
-
- PrintWriter out=new PrintWriter(s.getOutputStream(),true);
-
- out.println("客户端你好");
-
- s.close();
-
- ss.close();
- }
- }
运行自定义服务器后,在浏览器输入地址:http://172.16.56.237:1005/
172.16.56.237
GET / HTTP/1.1
Host: 172.16.56.237:1005
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like G
ecko) Chrome/21.0.1180.83 Safari/537.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8
Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3
这些都是浏览器向服务器发送请求的信息。包含浏览器的信息。
-
-
- import java.io.*;
- import java.net.*;
- class MyIE
- {
- public static void main(String[] args)throws Exception
- {
- Socket s=new Socket("172.16.56.237",8080);
-
- PrintWriter out=new PrintWriter(s.getOutputStream(),true);
-
- out.println("GET /myweb/index.html HTTP/1.1");
- out.println("Accept: */*");
- out.println("Accept-Language: zh-CN");
- out.println("Host: 172.16.56.237:1005");
- out.println("Connection: closed");
-
- out.println();
- out.println();
-
-
-
- BufferedReader bufr=new BufferedReader(new InputStreamReader(s.getInputStream()));
-
- String line=null;
- while((line=bufr.readLine())!=null)
- {
- System.out.println(line);
- }
-
- s.close();
-
- }
- }
七、网络编程(自定义图形界面浏览器-Tomcat服务端)
-
-
-
- import java.awt.*;
- import java.awt.event.*;
- import java.io.*;
- import java.net.*;
-
- class MyIEByGUI
- {
- private Frame f;
- private TextField tf;
- private Button but;
- private TextArea ta;
-
- private Dialog d;
- private Label lab;
- private Button okBut;
-
- MyIEByGUI()
- {
- init();
- }
- public void init()
- {
- f=new Frame("my window");
- f.setBounds(300,100,600,500);
- f.setLayout(new FlowLayout());
-
- tf=new TextField(60);
- but=new Button("转到");
- ta=new TextArea(25 ,70);
-
-
- d=new Dialog(f,"提示信息",true);
- d.setBounds(400,200,240,150);
- d.setLayout(new FlowLayout());
- lab=new Label();
- okBut=new Button("确定");
- d.add(lab);
- d.add(okBut);
-
- f.add(tf);
- f.add(but);
- f.add(ta);
-
- myEvent();
-
- f.setVisible(true);
- }
- private void myEvent()
- {
- but.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- try
- {
- showDir();
- }
- catch (Exception ee)
- {
- String info="您输入的地址是错误的,请重新输入!";
- lab.setText(info);
- d.setVisible(true);
- }
-
- }
- });
-
- f.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- System.exit(0);
- }
- });
-
- tf.addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent e)
- {
- try
- {
- if(e.getKeyCode()==KeyEvent.VK_ENTER)
- showDir();
- }
- catch (Exception ee)
- {
- String info="您输入的地址是错误的,请重新输入!";
- lab.setText(info);
- d.setVisible(true);
- }
-
- }
- });
- okBut.addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent e)
- {
- if(e.getKeyCode()==KeyEvent.VK_ENTER)
- d.setVisible(false);
- }
- });
-
- d.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- d.setVisible(false);
- }
- });
- okBut.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- d.setVisible(false);
- }
-
- });
- }
- private void showDir()throws Exception
- {
- ta.setText("");
-
- String url=tf.getText();
-
- int index1=url.indexOf("//")+2;
- int index2=url.indexOf("/",index1);
-
- String str=url.substring(index1,index2);
- String[] arr=str.split(":");
- String host=arr[0];
- int port=Integer.parseInt(arr[1]);
-
-
- String path=url.substring(index2);
-
-
-
-
- Socket s=new Socket(host,port);
-
- PrintWriter out=new PrintWriter(s.getOutputStream(),true);
-
- out.println("GET "+path+" HTTP/1.1");
- out.println("Accept: */*");
- out.println("Accept-Language: zh-CN");
- out.println("Host: 172.16.56.237:1005");
- out.println("Connection: closed");
-
- out.println();
- out.println();
-
-
-
- BufferedReader bufr=new BufferedReader(new InputStreamReader(s.getInputStream()));
-
- String line=null;
- while((line=bufr.readLine())!=null)
- {
- ta.append(line+"\r\n");
- }
-
- s.close();
- }
-
- public static void main(String[] args)
- {
- new MyIEByGUI();
- }
- }
八、网络编程(URL-URLConnection)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- import java.net.*;
- import java.io.*;
- class URLDemo
- {
- public static void main(String[] args)throws MalformedURLException
- {
- URL url=new URL("http://172.16.56.237/myweb/index.html?name=yangcheng&age=21");
-
- System.out.println("getProtocol:"+url.getProtocol());
- System.out.println("getHost:"+url.getHost());
- System.out.println("getPort:"+url.getPort());
- System.out.println("getPath:"+url.getPath());
- System.out.println("getFile:"+url.getFile());
- System.out.println("getQuery:"+url.getQuery());
-
-
-
-
-
-
-
- }
- }
-
-
-
-
- import java.net.*;
- import java.io.*;
- class URLConnectionDemo
- {
- public static void main(String[] args)throws Exception
- {
- URL url=new URL("http://172.16.56.237:8080/myweb/index.html");
-
- URLConnection conn=url.openConnection();
-
- InputStream in=conn.getInputStream();
- byte[] buf=new byte[1024];
- int len=in.read(buf);
- System.out.println(new String(buf,0,len));
-
- }
- }
既然如此,那么:
-
-
-
- import java.awt.*;
- import java.awt.event.*;
- import java.io.*;
- import java.net.*;
-
- class MyIEByGUI2
- {
- private Frame f;
- private TextField tf;
- private Button but;
- private TextArea ta;
-
- private Dialog d;
- private Label lab;
- private Button okBut;
-
- MyIEByGUI2()
- {
- init();
- }
- public void init()
- {
- f=new Frame("my window");
- f.setBounds(300,100,600,500);
- f.setLayout(new FlowLayout());
-
- tf=new TextField(60);
- but=new Button("转到");
- ta=new TextArea(25 ,70);
-
-
- d=new Dialog(f,"提示信息",true);
- d.setBounds(400,200,240,150);
- d.setLayout(new FlowLayout());
- lab=new Label();
- okBut=new Button("确定");
- d.add(lab);
- d.add(okBut);
-
- f.add(tf);
- f.add(but);
- f.add(ta);
-
- myEvent();
-
- f.setVisible(true);
- }
- private void myEvent()
- {
- but.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- try
- {
- showDir();
- }
- catch (Exception ee)
- {
- String info="您输入的地址是错误的,请重新输入!";
- lab.setText(info);
- d.setVisible(true);
- }
-
- }
- });
-
- f.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- System.exit(0);
- }
- });
-
- tf.addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent e)
- {
- try
- {
- if(e.getKeyCode()==KeyEvent.VK_ENTER)
- showDir();
- }
- catch (Exception ee)
- {
- String info="您输入的地址是错误的,请重新输入!";
- lab.setText(info);
- d.setVisible(true);
- }
-
- }
- });
- okBut.addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent e)
- {
- if(e.getKeyCode()==KeyEvent.VK_ENTER)
- d.setVisible(false);
- }
- });
-
- d.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- d.setVisible(false);
- }
- });
- okBut.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- d.setVisible(false);
- }
-
- });
- }
- private void showDir()throws Exception
- {
- ta.setText("");
-
- String urlPath=tf.getText();
-
- URL url=new URL(urlPath);
-
- URLConnection conn=url.openConnection();
-
- InputStream in=conn.getInputStream();
- byte[] buf=new byte[1024];
- int len=in.read(buf);
- ta.setText(new String(buf,0,len));
- }
-
- public static void main(String[] args)
- {
- new MyIEByGUI2();
- }
- }
九、网络编程(小知识点)
Socket类:
Socket() :通过系统默认类型的 SocketImpl 创建未连接套接字
void connect(SocketAddress endpoint) :将此套接字连接到服务器。
InetSocketAddress类:
而:InetSocketAddress继承自SocketAddress
InetSocketAddress类实现 IP 套接字地址(IP 地址 + 端口号)。它还可以是一个对(主机名 + 端口号),在此情况下,将尝试解析主机名。如果解析失败,则该地址将被视为未解析 地址,但是其在某些情形下仍然可以使用,比如通过代理连接。
而InetAddress类实现 IP地址。
ServerSocket类:
public ServerSocket(int port,int backlog)throws IOException
利用指定的 backlog 创建服务器套接字并将其绑定到指定的本地端口号。
端口号 0 在所有空闲端口上创建套接字。
port - 指定的端口;或者为 0,表示使用任何空闲端口。
backlog - 队列的最大长度。也就是联机数。
十、网络编程(域名解析)
例如:
要访问www.baidu.com
先查看本地的hosts文件(域名和对应的IP缓存)有没有www.baidu.com的IP。有的话,直接到hosts文件www.baidu.com对应的IP地址去访问。如果没有则会去DNS服务器找www.baidu.com的对应IP。
hosts文件最常用来屏蔽危险连接。例如将不安全的域名直接在hosts文件中和127.0.0.1回环地址绑定。这个危险的网站就不会去DNS服务器找IP了,网站也就无法打开。