Java基础知识 十六 (网络编程)

1:网络编程
 (1)网络编程:用Java语言实现计算机间数据的信息传递和资源共享


 (2)网络编程模型


 (3)网络编程的三要素:
  A:IP地址
   a:点分十进制
   b:IP地址的组成
   c:IP地址的分类
   d:dos命令
   e:InetAddress
  B:端口
   是应用程序的标识。范围:0-65535。其中0-1024不建议使用。
  C:协议
   UDP:数据打包,有限制,不连接,效率高,不可靠
   TCP:建立数据通道,无限制,效率低,可靠


 (3)Socket机制
  A:通信两端都应该有Socket对象
  B:所有的通信都是通过Socket间的IO进行操作的


 (4)UDP协议发送和接收数据

  发送:
   创建UDP发送端的Socket对象
   创建数据并把数据打包
   发送数据
   释放资源
   
  接收:
   创建UDP接收端的Socket对象
   创建数据包用于接收数据
   接收数据
   解析数据包
   释放资源


 (5)TCP协议发送和接收数据

  发送:
   创建TCP客户端的Socket对象
   获取输出流,写数据
   释放资源
   
  接收:
   创建TCP服务器端的Socket对象
   监听客户端连接
   获取输入流,读取数据
   释放资源

 

案例

awt+IO实现用户的登陆注册
 |-- 界面
 |-- 登陆功能


import java.io.*;
public class User {
 //返回真,用户登陆成功
 public boolean login(String username,Stringpassword){
  //获取到用户名和密码,读取文本文件,查找匹配
  BufferedReader bfr =null;
  try{
   bfr = newBufferedReader(new FileReader("c:\\text.txt"));
   String line =null;
   while((line =bfr.readLine())!=null){
    //System.out.println(line);//shisong=123
    String[]s = line.split("=");
    if(username.equals(s[0])&&password.equals(s[1]))
     returntrue;
   }
  }catch(IOException e){
   System.out.println(e);
   throw newRuntimeException("读取文件失败");
  }finally{
   try{
    if(bfr!=null)
     bfr.close();
   }catch(IOExceptione){
    thrownew RuntimeException("读取关闭失败");
   }
  }
  return false;
 }
 //检测用户名是否存在,存在返回真
 public boolean login(String username){
  //获取到用户名和密码,读取文本文件,查找匹配
  BufferedReader bfr =null;
  try{
   bfr = newBufferedReader(new FileReader("c:\\text.txt"));
   String line =null;
   while((line =bfr.readLine())!=null){
    //System.out.println(line);//shisong=123
    String[]s = line.split("=");
    if(username.equals(s[0]))
     returntrue;
   }
  }catch(IOException e){
   System.out.println(e);
   throw newRuntimeException("读取文件失败");
  }finally{
   try{
    if(bfr!=null)
     bfr.close();
   }catch(IOExceptione){
    thrownew RuntimeException("读取关闭失败");
   }
  }
  return false;
 }
 
 //将用户名和密码,写入文件,进行永久性保存
 public void regedit(String username,Stringpassword){
  FileWriter fw = null;
  try{
   fw = newFileWriter("c:\\text.txt",true);
   String text =username+"="+password;
   fw.write(text+"\r\n");
   fw.flush();
  }catch(IOException e){
   System.out.println(e);
   throw newRuntimeException("文件写入失败");
  }finally{
   try{
    if(fw!=null)
     fw.close();
   }catch(IOExceptione){
    thrownew RuntimeException("文件写入关闭失败");
   }
  }
 }
 //获取所有用户信息的方法
 public String allUserList(){
  StringBuilder sb = newStringBuilder();
  BufferedReader bfr =null;
  try{
   bfr = newBufferedReader(new FileReader("c:\\text.txt"));
   String line =null;
   while((line =bfr.readLine())!=null){
    sb.append(line+"\r\n");
   }
  }catch(IOException e){
   System.out.println(e);
   throw newRuntimeException("读取文件失败");
  }finally{
   try{
    if(bfr!=null)
     bfr.close();
   }catch(IOExceptione){
    thrownew RuntimeException("文件读取关闭失败");
   }
  }
  return sb.toString();
 
}

import java.awt.*;
import java.awt.event.*;
public class FrameRegedit {
 public FrameRegedit(){
  init();
 }
 private Frame frm = null;
 private Label message =null,usernamelbl=null,passwordlbl=null,repasswordlbl=null;
 //文本框
 private TextField usernametf = null, passwordtf =null,repasswordtf = null;
 //3个按钮
 privateButton  regeditbut =null, quitbut= null;
 
 private void init(){
  frm = new Frame("用户注册");
  frm.setBounds(300, 100, 500,350);
  frm.setBackground(Color.gray);
  frm.setLayout(null);
  frm.setVisible(true);
  
  message = newLabel("用户的登陆和注册");
  message.setBounds(150, 50, 100,30);
  frm.add(message);
  
  usernamelbl = newLabel("用户名");
  usernamelbl.setBounds(100, 100,50, 30);
  frm.add(usernamelbl);
  
  usernametf = newTextField();
  usernametf.setBounds(160, 105,150, 20);
  frm.add(usernametf);
  
  passwordlbl = newLabel("密  码");
  passwordlbl.setBounds(100, 150,50, 30);
  frm.add(passwordlbl);
  
  passwordtf = newTextField();
  passwordtf.setBounds(160, 150,150, 20);
  frm.add(passwordtf);
  
  repasswordlbl = newLabel("确认密码");
  repasswordlbl.setBounds(100,200, 50, 30);
  frm.add(repasswordlbl);
  
  repasswordtf = newTextField();
  repasswordtf.setBounds(160,200, 150, 20);
  frm.add(repasswordtf);
  
  regeditbut = newButton("确认注册");
  regeditbut.setBounds(200, 250,80, 30);
  frm.add(regeditbut);
  myEvent();
 }
 private void myEvent(){
  regeditbut.addActionListener(newActionListener() {
 
   public voidactionPerformed(ActionEvent e) {
    //获取用户名密码,确认密码
    Stringusername = usernametf.getText();
    Stringpassword = passwordtf.getText();
    Stringrepassword = repasswordtf.getText();
    if("".equals(username)||"".equals(password)||"".equals(repassword))
     return;
    if(!(password.equals(repassword))){
     System.out.println("两次密码不一致");
     return;
    }
    //检测用户名是否存在
    booleanb = new User().login(username);
    if(b){
     System.out.println("用户名存在");
    }else{
     //调用IO中的功能,将用户名和密码写入文件保存
     newUser().regedit(username, repassword);
     System.out.println("注册成功");
     frm.setVisible(false);
    }
   }
  });
 }
}

import java.awt.*;
import java.awt.event.*;
public class FrameLogin {
 public FrameLogin(){
  init();
 }
 //窗体
 private Frame frm = null;
 private Label message =null,usernamelbl=null,passwordlbl=null;
 //文本框
 private TextField usernametf = null, passwordtf =null;
 //3个按钮
 private Button loginbut = null, regeditbut =null,quitbut = null;
 private void init(){
  frm = new Frame("用户登陆");
  frm.setBounds(300, 100, 500,350);
  frm.setBackground(Color.gray);
  frm.setLayout(null);
  frm.setVisible(true);
  
  message = newLabel("用户的登陆和注册");
  message.setBounds(150, 50, 100,30);
  frm.add(message);
  
  usernamelbl = newLabel("用户名");
  usernamelbl.setBounds(100, 100,50, 30);
  frm.add(usernamelbl);
  
  usernametf = newTextField();
  usernametf.setBounds(160, 105,150, 20);
  frm.add(usernametf);
  
  passwordlbl = newLabel("密  码");
  passwordlbl.setBounds(100, 150,50, 30);
  frm.add(passwordlbl);
  
  passwordtf = newTextField();
  passwordtf.setBounds(160, 150,150, 20);
  passwordtf.setEchoChar('你');
  frm.add(passwordtf);
  
  loginbut = newButton("登陆");
  regeditbut = newButton("注册");
  
  loginbut.setBounds(150, 200,50, 20);
  regeditbut.setBounds(250, 200,50, 20);
  
  frm.add(loginbut);
  frm.add(regeditbut);
  myEvent();
 }
 private void myEvent(){
  loginbut.addActionListener(newActionListener() {
   public voidactionPerformed(ActionEvent e) {
    Stringusername = usernametf.getText();
    Stringpassword = passwordtf.getText();
    if("".equals(username)||"".equals(password))
     return;
    //有了用户名和密码,到文本文件中,查找有没有这个匹配的用户名和密码
    booleanb = new User().login(username, password);
    if(b){
      newAllUserList();
    }else{
     System.out.println("登陆失败,检查用户名和密码");
    }
   }
  });
  
  regeditbut.addActionListener(newActionListener() {
   public voidactionPerformed(ActionEvent e) {
    //打开注册的窗体
    newFrameRegedit();
   }
  });
 }
}
import java.awt.*;
public class AllUserList {
 public AllUserList(){
  init();
  
 }
 private Frame frm = null;
 private TextArea ta = null;
 private void init() {
  frm = newFrame("展示所有用户的信息");
  frm.setBounds(300, 100, 500,350);
  frm.setBackground(Color.gray);
  frm.setLayout(null);
  frm.setVisible(true);
  ta = new TextArea();
  ta.setBounds(50, 35, 400,300);
  frm.add(ta);
  String s = newUser().allUserList();
  ta.setText("");
  ta.append(s);
 }
 
}
public class Test {
 public static void main(String[] args) {
  new FrameLogin();
 }
}

5. 网络通讯的三要素
  |-- IP地址
    |--接入互联网的计算的,唯一的身份标识  222.222.123.23   www.baidu.com.cn  edugov org 
    |--本机回环地址 127.0.0.1 localhost ,只要你的机器的网卡是好的,安装了驱动
    |--java中,将IP地址,封装成对象,java.net.InetAddress
    |--InetAddress私有构造,找静态方法,返回这个类的对象
      |--getName("主机名")根据主机名,获取该主机的IP地址对象
      |--getLocalHost()获取本机IP地址对象
      |--通过IP地址对象,单独获取IP 和主机名

  |-- 端口号
    |--用于标识进程的逻辑地址,不同进程的标识(十进制数)
    |--有效端口:0~65535,其中0~1024系统使用或保留端口。
    |--常见端口 80,1433 ,1521,3306
    |--注意:一个端口号上,只能有一个应用程序

  |-- 协议
    |--UDP
      |--面向无连接
      |--发送的数据有限制 64K
      |--不安全的协议
      |--效率高
    |--TCP
      |--面向连接
      |--传输大数据
      |--安全可靠
      |--效率低

6. Socket服务
  |-- 港口,快递
  |-- 发送和接收都需要有Socket服务

7. UDP的发送端
  |--DatagramSocket对象即可发送,也可以接收
  |-- 发送数据的步骤
    |--先要有数据
    |--将数据封包DatagramPacket
        DatagramPacket(byte[]buf, int length, InetAddress address, int port)
    |--发送
    |--关闭资源

9. UDP的接收端
  |--DatagramSocket对象即可发送,也可以接收
  |-- 先建立Socket服务,监听端口
  |-- 接收 voidreceive(DatagramPacket p) 数据包
  |-- 解包
  |-- 关闭资源

10. 多线程的聊天程序,案例*****

import java.net.*;

public class TestUDP {
 public static void main(String[] args) throwsException{
  //建立Socket对象,将Socket对象传给多线程程序
  //建立发送端的Socket服务
  DatagramSocket dsSend = newDatagramSocket(8000);
  DatagramSocket dsReceive = newDatagramSocket(10000);
  
  ThreadUDPSend ts = newThreadUDPSend(dsSend);
  ThreadUDPReceive tr = newThreadUDPReceive(dsReceive);
  
  new Thread(ts).start();
  new Thread(tr).start();
 }

}
import java.net.*;
public classThreadUDPReceive  implementsRunnable{
 private DatagramSocket ds;
 public ThreadUDPReceive(DatagramSocket ds){this.ds = ds;}
   public voidrun(){
    while(true){
     try{
     byte[]buf = new byte[1024];
     DatagramPacketdp = new DatagramPacket(buf, 0,buf.length);
     ds.receive(dp);
     //获取数组中的有效长度
     intlength = dp.getLength();
     //获取发送的IP地址
     Stringip = dp.getAddress().getHostAddress();
     intport = dp.getPort();//端口号
     Stringmessage = new String(buf,0,length);
     if("over".equals(message)){
      System.out.println(ip+"::"+port+"::退出聊天室");
     }
     System.out.println(ip+"::"+port+"::"+message);
     }catch(Exceptione){}
    }
   }
}

import java.net.*;
import java.io.*;

public class ThreadUDPSend implements Runnable{
 private DatagramSocket ds;
 public ThreadUDPSend(DatagramSocket ds){ this.ds= ds;}
 public void run(){
  BufferedReader bfr =null;
  try{
   bfr =new
    BufferedReader(newInputStreamReader(System.in));
  String line = null;
  while((line =bfr.readLine())!=null){
   if("over".equals(line))
    break;
   //封装数据包
   byte[] buf =line.getBytes();
   DatagramPacketdp =
     newDatagramPacket(buf,0,buf.length,InetAddress.getByName("127.0.0.1"),10000);
   ds.send(dp);
    }
  }
  catch(IOException e){
   System.out.println(e);
   throw newRuntimeException("发送失败");
  }finally{
   try{
    if(bfr!=null)
     bfr.close();
   }catch(IOExceptione){}
   
   ds.close();
  }
 }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值