黑马程序员--网络编程笔记总结

 

 

 

 

UDP1.面向无连接,无需建立连接,比如视频直播,feiq,我屏幕录像

2.数据会被封包,数据有限制,在64k

3.不可靠

4.速度快

TCP1.面向连接,必须建立连接,需要三次握手,比如打电话

      2.数据传输量大,不用封装包

3.可靠

4.速度有点慢

 

            Socket

Socket是为网络服务提供的一种机制

通信两端都有socket

网络通信其实就是socket间的通信

数据在两个socket间通过IO传输

DatagramSocket此类表示用来发送和接收数据报包的套接字。 数据报套接字是包投递服务的发送或接收点。每个在数据报套接字上发送或接收的包都是单独编址和路由的。从一台机器发送到另一台机器的多个包可能选择不同的路由,也可能按不同的顺序到达

DatagramPacket数据报包用来实现无连接包投递服务。每条报文仅根据该包中包含的信息从一台机器路由到另一台机器。从一台机器发送到另一台机器的多个包可能选择不同的路由,也可能按不同的顺序到达。不对包投递做出保证。

 

UDP练习

/*

通过upd传输数据

1.建立updsocket服务点

2.提供数据,并封装数据

3,通过socket服务功能发送数据出去

4.关闭资源

*/

 

import java.net.*;

class Udpsend 

{

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

{

//建立updsocket服务店点

DatagramSocket ds=new DatagramSocket();

//提供数据,并封装数据DatagramPacket(byte[] buf, int length, InetAddress address, int port) 

         // 构造数据报包,用来将长度为 length 的包发送到指定主机上的指定端口号。

byte[] data="wo lai le ni zai na".getBytes();

DatagramPacket dg=

new DatagramPacket(data,data.length,InetAddress.getByName("192.168.2.71"),10000);

//通过socket发送数据

ds.send(dg);//通过Socket将打包的dg发送出去

ds.close();

 

 

}

}

/*

定义一个应用程序,

1.定义udpsocket服务

2.定义个数据包,因为要存储接受到的字节数据因为该包对象中有

更多功能可以提取字节数据中的不同数据信息。

3.通过Socket服务的receive方法将收到的数据存入定义好的数据包中

4,通过数据包对象的特有功能将这些不同的数据取出

5,关闭资源

 

 

*/

class Udpreceive

{

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

{

DatagramSocket ds=new DatagramSocket(10000);//定义个数据接收端

byte[] by=new byte[1024];

DatagramPacket dp=new DatagramPacket(by,by.length);//定义个数据接收包,用于存储接收到的数据信息

ds.receive(dp);//通过数据包的接收功能receive存储接收到的数据信息这是阻塞式方法,也就是线程到这里就停了,有数据就执行,没有事数据就等。

String ip=dp.getAddress().getHostAddress();//获取主机名

String data=new String(dp.getData(),0,dp.getLength());

int port=dp.getPort();//获取发送主机的端口号

System.out.println(ip+"::"+data+"::"+port);

ds.close();

 

 

}

}

 

       多线程收发信息

import java.io.*;

import java.net.*;

class Send implements Runnable

{

private DatagramSocket ds;

public Send(DatagramSocket ds)

{

this.ds=ds;

}

public void run()

{

try

{

BufferedReader br=

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

String line=null;

while ((line=br.readLine())!=null)

{

if("886".equals(line))

break;

byte[] by=(line).getBytes();

DatagramPacket dp=

new DatagramPacket(by,by.length,InetAddress.getByName("192.168.2.255"),2000);//255是表示赋给192.168.2.这个局域内的 所有主机

ds.send(dp);

}

}

catch (Exception e)

{

throw new RuntimeException("发送失败!");

}

 

}

 

}

 

class Receive implements Runnable

{

private DatagramSocket ds;

public Receive(DatagramSocket ds)

{

this.ds=ds;

}

public void run()

{

try

{

while (true)

{byte[] by=new byte[1024];

DatagramPacket dp=new DatagramPacket(by,by.length);//创建一个接收by.length的数据包

ds.receive(dp);//ds接收到的 数据存入dp包中

String data=new String(dp.getData(),0,dp.getLength());//获取接收到的数据

String ip=dp.getAddress().getHostAddress();//获取ip

System.out.println(ip+"::  "+data);

 

}

 

}

catch (Exception e)

{

throw new RuntimeException("接收失败!");

}

}

}

class Udpthread 

{

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

{

DatagramSocket send=new DatagramSocket();

DatagramSocket receive=new DatagramSocket(2000);

new Thread(new Send(send)).start();//创建发信息线程

new Thread(new Receive(receive)).start();//创建收信息线程

 

}

}

                 

 

                     TCP

在建立socket服务是,就要服务端存在,并连接成功,形成通路,可以再该通道进行数据交流

客服端:

步骤

1.创建socket服务,并指定连接主机名和端口

 

 

/*

需求,定义端口接收数据并打印在控制台上

服务端

1,建立服务端的serversocket

  并监听一个端口

  2.获取连接过来的 客服端对象

  通过serversocketaccept方法连接

  所以这个方法是阻塞式的没有连接就回等

  3,客服端,如果发过来数据,服务端,使用客服端对象,并获取到该客服端对象的

  读取流,读取发过来的数据,并打印在控制台

  4

*/

 

客服端

源,:键盘

目的,网络设备,网络输出流

而且操作的是文本数据,可以选择字符流

 

 

           TCP小练习

      服务端与客服端的交流

 

import java.io.*;

import java.net.*;

class  Server

{

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

{

ServerSocket ss=new ServerSocket(10004);//创建一个连接到特点端口的服务器

Socket s=ss.accept();//通过accept获取接受到的连接

//创建一个从客服端获取数据的输入流的缓冲区

BufferedReader bin=

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

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

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

//创建一个输出流的 缓冲区

//BufferedWriter bout=

//new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

PrintWriter pw=

new PrintWriter(s.getOutputStream(),true);// 通过现有的 OutputStream 创建新的 PrintWriter  true代表刷新

String line=null;

while ((line=bin.readLine())!=null)

{

System.out.println(line);

pw.println(line.toUpperCase());

//bout.write(line.toUpperCase());

//bout.newLine();//换行

//bout.flush();

}

ss.close();

 

}

}

class  Clien

{

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

{

Socket s=new Socket("192.168.2.71",10004);//创建一个连接到指定地址的端口号

BufferedReader bfr=

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

//创建一个从服务器获取数据的输入流的缓冲区

BufferedReader bin=

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

//创建一个输出流的 缓冲区

//BufferedWriter bout=

//new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

PrintWriter pw=

new PrintWriter(s.getOutputStream(),true);// 通过现有的 OutputStream 创建新的 PrintWriter true代表刷新,

String line=null;//创建一个读取一行的字符串

while ((line=bfr.readLine())!=null)

{

if("over".equals(line))

break;

pw.println(line);

//bout.write(line);

//bout.newLine();//换行

//bout.flush();

String str=bin.readLine();//获取从服务端返回来的数据

System.out.println(str);

}

s.close();

bfr.close();

 

}

}

 

 

 

                          JavaTcp进行文件复制

import java.io.*;

import java.net.*;

class  TcpCopyClien

{

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

{

Socket s=new Socket("192.168.2.71",10009);

BufferedReader br=

new BufferedReader(new FileReader("Tcpdemo.java"));//创建一个读取文件源

PrintWriter pw=new PrintWriter(s.getOutputStream(),true);//socket获取输出流

 

String line=null;

while ((line=br.readLine())!=null)

{

pw.println(line);

}

s.shutdownOutput();//关闭输出流,相当于给输出流加上一个结束标记

BufferedReader bin=

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

System.out.println(bin.readLine());

 

br.close();

s.close();

}

}

class  TcpCopyServer

{

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

{

ServerSocket ss=new ServerSocket(10009);

Socket s=ss.accept();//获取所有接收到的 数据源

BufferedReader br=

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

String ip=s.getInetAddress().getHostAddress();//获取IP

System.out.println(ip);

PrintWriter pw=new PrintWriter(new FileWriter("server.txt"),true);//创建文件打印

String line=null;

while ((line=br.readLine())!=null)

{

pw.println(line);

}

 

PrintWriter out=new PrintWriter(s.getOutputStream(),true);//创建输出流

out.println("上传成功!");

 

ss.close();

s.close();

pw.close();

 

 

 

 

 

}

}

 

                           Tcp图片 从客服端上传到服务端参考代码

 

import java.io.*;

import java.net.*;

class  PicClien

{

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

{

Socket s=new Socket("192.168.2.71",10009);

FileInputStream fis=new FileInputStream("d:\\2.jpg");

OutputStream os=s.getOutputStream();//从套接字获取输出流

byte[] by=new byte[1024];

int len=0;

while ((len=fis.read(by))!=-1)

{

os.write(by,0,len);

}

s.shutdownOutput();

InputStream is=s.getInputStream();//从套接字获取输入流

byte[] bys=new byte[1024];//创建一个缓冲区

int lens=is.read(bys);

System.out.println(new String(bys,0,lens));

s.close();

fis.close();

 

}

}

class  PicServer

{

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

{

ServerSocket ss=new ServerSocket(10009);

Socket s=ss.accept();//获取所有接收到的 数据源

InputStream is=s.getInputStream();//从套接字获取输入流

 

FileOutputStream fos=new FileOutputStream("picserver.jpg");

byte[] by=new byte[1024];

int len=0;

while ((len=is.read(by))!=-1)

{

fos.write(by,0,len);

}

OutputStream out =s.getOutputStream();

out.write("上传成功".getBytes());

ss.close();

s.close();

fos.close();

 

}

}

 

 

 

TCP 多个客服端并发访问服务器传送图片

 

 

/*\

为了可以让多个客服同时并发访问服务端 

那么服务端最好就是将每个客服端封装成一个单独的 线程中,这样就可以同时处理多个客服端

 

*/

import java.io.*;

import java.net.*;

class  LoadPicClien3

{

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.isFile()&&file.exists()))

{

System.out.println("该文件不存在");

return;

}

if(!file.getName().endsWith(".jpg"))

{

System.out.println("该文件不是jpg文件,请从新上传");

return;

}

if(file.length()>1024*1024*6)

{

System.out.println("请上传6M以内的文件");

return;

}

Socket s=new Socket("192.168.2.71",10009);

FileInputStream fis=new FileInputStream(file);

OutputStream os=s.getOutputStream();//从套接字获取输出流

byte[] by=new byte[1024];

int len=0;

while ((len=fis.read(by))!=-1)

{

os.write(by,0,len);

}

s.shutdownOutput();

InputStream is=s.getInputStream();//从套接字获取输入流

byte[] bys=new byte[1024];//创建一个缓冲区

int lens=is.read(bys);

System.out.println(new String(bys,0,lens));

s.close();

fis.close();

 

}

}

 

class  LoadPicClien2

{

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.isFile()&&file.exists()))

{

System.out.println("该文件不存在");

return;

}

if(!file.getName().endsWith(".jpg"))

{

System.out.println("该文件不是jpg文件,请从新上传");

return;

}

if(file.length()>1024*1024*6)

{

System.out.println("请上传6M以内的文件");

return;

}

Socket s=new Socket("192.168.2.71",10009);

FileInputStream fis=new FileInputStream(file);

OutputStream os=s.getOutputStream();//从套接字获取输出流

byte[] by=new byte[1024];

int len=0;

while ((len=fis.read(by))!=-1)

{

os.write(by,0,len);

}

s.shutdownOutput();

InputStream is=s.getInputStream();//从套接字获取输入流

byte[] bys=new byte[1024];//创建一个缓冲区

int lens=is.read(bys);

System.out.println(new String(bys,0,lens));

s.close();

fis.close();

 

}

}

 

class  LoadPicClien1

{

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.isFile()&&file.exists()))

{

System.out.println("该文件不存在");

return;

}

if(!file.getName().endsWith(".jpg"))

{

System.out.println("该文件不是jpg文件,请从新上传");

return;

}

if(file.length()>1024*1024*6)

{

System.out.println("请上传6M以内的文件");

return;

}

Socket s=new Socket("192.168.2.71",10009);

FileInputStream fis=new FileInputStream(file);

OutputStream os=s.getOutputStream();//从套接字获取输出流

byte[] by=new byte[1024];

int len=0;

while ((len=fis.read(by))!=-1)

{

os.write(by,0,len);

}

s.shutdownOutput();

InputStream is=s.getInputStream();//从套接字获取输入流

byte[] bys=new byte[1024];//创建一个缓冲区

int lens=is.read(bys);

System.out.println(new String(bys,0,lens));

s.close();

fis.close();

 

}

}

 

class  LoadPicClien

{

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.isFile()&&file.exists()))

{

System.out.println("该文件不存在");

return;

}

if(!file.getName().endsWith(".jpg"))

{

System.out.println("该文件不是jpg文件,请从新上传");

return;

}

if(file.length()>1024*1024*6)

{

System.out.println("请上传6M以内的文件");

return;

}

Socket s=new Socket("192.168.2.71",10009);

FileInputStream fis=new FileInputStream(file);

OutputStream os=s.getOutputStream();//从套接字获取输出流

byte[] by=new byte[1024];

int len=0;

while ((len=fis.read(by))!=-1)

{

os.write(by,0,len);

}

s.shutdownOutput();

InputStream is=s.getInputStream();//从套接字获取输入流

byte[] bys=new byte[1024];//创建一个缓冲区

int lens=is.read(bys);

System.out.println(new String(bys,0,lens));

s.close();

fis.close();

 

}

}

 

class ThreadLoad implements Runnable

{

private Socket s;

ThreadLoad(Socket s)

{

this.s=s;

}

public void run()

{

int count=1;

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

try

{

InputStream is=s.getInputStream();//从套接字获取输入流

File file=new File(ip+"("+(count)+")"+".jpg");

while(file.exists())

 file=file=new File(ip+"("+(count++)+")"+".jpg");

FileOutputStream fos=new FileOutputStream(file);

byte[] by=new byte[1024];

int len=0;

while ((len=is.read(by))!=-1)

{

fos.write(by,0,len);

}

OutputStream out =s.getOutputStream();

out.write("上传成功".getBytes());

s.close();

 

fos.close();

}

catch (Exception e)

{

throw new RuntimeException("上传失败");

}

 

 

}

 

}

class  LoadPicServer

{

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

{

ServerSocket ss=new ServerSocket(10009);

while (true)

{

Socket s=ss.accept();//获取所有接收到的 数据源

new Thread(new ThreadLoad(s)).start();//没收到一个客服端,请求就创建一个线程

}

 

}

}

 

  TCP客服端并发登录

import java.io.*;

import java.net.*;

class LoginClien 

{

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

{

Socket s=new Socket("192.168.2.71",1004);//创建一个连接到指定地址的端口号

BufferedReader bfr=

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

//创建一个从服务器获取数据的输入流的缓冲区

BufferedReader bin=

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

PrintWriter pw=

new PrintWriter(s.getOutputStream(),true);// 通过现有的 OutputStream 创建新的 PrintWriter true代表刷新,

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

{

    String username=bfr.readLine();//从键盘获取用户名

if(username==null)

{

System.out.println("用户名不能为空!!");

break;

}

pw.println(username);

String info=bin.readLine();

System.out.println(info);

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

break;

 

}

//System.out.println("系统发现你在恶意登录,现在暂停你的账号1小时");

s.close();

bfr.close();

}

}

class LoginThread implements Runnable

{

private Socket s;

LoginThread(Socket s)

{

this.s=s;

 

}

public void run()

{

String ip=s.getInetAddress().getHostAddress();//获取IP

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

try

{

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

{

BufferedReader br=

new BufferedReader(new InputStreamReader(s.getInputStream()));//从套接字获取输入信息

String username=br.readLine();

if(username==null)

break;

BufferedReader bfr=

new BufferedReader(new FileReader("userinfo.txt"));

PrintWriter pw=

new PrintWriter(s.getOutputStream(),true);//从套接字获取输出信息

String line=null;

boolean flag=false;

while ((line=bfr.readLine())!=null)

{

if(username.equals(line))

{

flag=true;

break;

}

}

if(flag!=true)

{

if(x>=2)

   pw.println("系统发现你恶意登录,现已暂停你1小时");

pw.println(username+"::"+"登录名有误,情重新登录");

System.out.println("登录名有误,请重新登录");

 

}

else

{

pw.println(username+"...登录成功,欢迎光临");

System.out.println("登录成功,欢迎光临");

break;

}

 

 

}

 

s.close();

}

catch (Exception e)

{

throw new RuntimeException("用户登录失败");

}

 

}

 

}

 

class LoginServer 

{

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

{

ServerSocket ss=new ServerSocket(1004);

while (true)

{

Socket s=ss.accept();

new Thread(new LoginThread(s)).start();

 

}

}

}

 

 

 

 通过URL 自己做的浏览器

 

//本程序前提是必须要有Tomcat服务器,打开后才能运行

//否则自己做一个服务器

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.util.*;

import java.net.*;

class MyIEGui 

{

private static Frame f;

private static Button but;

private static TextField tf;

private static Dialog dl;

private static Label lab;

private static Button okbut;

private static TextArea ta;

public static void main(String[] args) 

{

   init();

}

private static void init()

{

f=new Frame("my window");

f.setBounds(300,200,500,400);

f.setLayout(new FlowLayout());

but=new Button("转到");

tf=new TextField(53);

ta=new TextArea(19,60);

f.add(tf);

f.add(but);

f.add(ta);

dl=new Dialog(f,"错误信息",true);

dl.setBounds(350,250,240,120);

dl.setLayout(new FlowLayout());

lab=new Label();

okbut=new Button("确定");

dl.add(lab);

dl.add(okbut);

event();

f.setVisible(true);

}

private static void event()

{

    tf.addKeyListener(new KeyAdapter(){

public void keyPressed(KeyEvent e)

{

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

{

  try

  {

show();

  }

  catch (Exception ee)

  {

  throw new RuntimeException("路径错误");

  }

    

}

}

});

okbut.addKeyListener(new KeyAdapter(){

public void keyPressed(KeyEvent e)

{

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

{

  try

  {

show();

  }

  catch (Exception es)

  {

  throw new RuntimeException("路径错误");

  }

    

}

}

});

f.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e)

{

System.exit(0);

}

});

dl.addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent e)

{

dl.setVisible(false);

}

});

okbut.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e)

{

dl.setVisible(false);

}

});

but.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

  try

  {

show();

  }

  catch (Exception ex)

  {

  throw new RuntimeException("路径错误");

  }

    

}

});

 

}

private static void show()throws Exception

{

ta.setText("");

String urlpath=tf.getText();//

URL url=new URL(urlpath);

URLConnection conn=url.openConnection();//它表示到 URL 所引用的远程对象的连接。

InputStream ins=conn.getInputStream();//获取连接读取的输入流

byte[] by=new byte[1024*1024*100];

int len=ins.read(by);

ta.append(new String(by,0,len));

 

 

}

 

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2012-11-30 21:20  杰的博客  阅读(338)  评论(0编辑  收藏  举报