------- android培训、java培训、期待与您交流! ----------
* 网络编程
* 网络模型
* OSI参考模型
* TCP/IP参考模型
* 网络通讯要素
* IP地址
* 端口号:应用程序都有对应的数字标识,以便于数据进行识别,这个数字标识就叫端口
* 传输协议,通讯规则,通用协议:TCP/IP
import java.net.*;
public class IPDemo
{
public static void main(String[] args) throws Exception
{
InetAddress i=InetAddress.getLocalHost();
System.out.println(i.toString());
//分别获取
System.out.println(i.getAddress());
System.out.println(i.getHostAddress());
System.out.println(i.getHostName());
//获取任意一台IP主机地址对象
InetAddress ip=InetAddress.getByName("dell-PC");
System.out.println(ip.toString());
}
}
* UDP:
* 将数据源和目的封装成数据包,不需要建立连接,(面向无连接)
* 大小每包64K
* 无连接是不可靠协议
* 无需建立连接,速度快
*
* TCP
* 建立连接,形成数据传输的通道
* 可进行大数据量的传输
* 可靠
* 效率低*/
//1,创建UDP服务,通过new DatagramSocket对象
;//对象里可以指定应用程序端口
//2,确定数据,并封装成数据包。打包数据用DatagramPacket(数据数组,数组长度,对方IP,对方端口)
//3,通过socket服务,将打包好的数据包发送
//4,关闭资源
import java.net.*;
class UDPSend
{
public void main(String[] args) throws Exception
{
//1,创建UDP服务,通过new DatagramSocket对象
DatagramSocket ds=new DatagramSocket();//对象里可以指定应用程序端口
//2,确定数据,并封装成数据包。打包数据用DatagramPacket(数据数组,数组长度,对方IP,对方端口)
byte[] bu="数据".getBytes();
DatagramPacket dp=new DatagramPacket(bu,bu.length,InetAddress.getByName("192.168.1.1"),10000);
//3,通过socket服务,将打包好的数据包发送出去
ds.send(dp);
//4,关闭资源
ds.close();
}
}
//1.创建UDP服务
//指定端口
//2,定义数据包,接受数据
//3,接受
//4,取出其中数据
//5,关闭资源
class UDPrece
{
public static void main(String[] args) throws Exception
{
//1.创建UDP服务
DatagramSocket ds=new DatagramSocket(10000);//指定端口
//2,定义数据包,接受数据
byte[] bu=new byte[1024];
DatagramPacket dp=new DatagramPacket(bu,bu.length);
//3,接受
ds.receive(dp);
//4,取出其中数据
String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength());
int port=dp.getPort();
//5,关闭资源
ds.close();
}
}
练习:
聊天程序
/*用多线程编写一个聊天程序
* 有收和发,需同时运行,多线程
* */
import java.net.*;
import java.io.*;
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("exit".equals(line))
break;
byte[] bu=line.getBytes();
DatagramPacket dp=
new DatagramPacket(bu,bu.length,InetAddress.getByName("127.0.0.1"),10000);
ds.send(dp);//发送包
}
}
catch(Exception e)
{
throw new RuntimeException("");
}
}
}
class Rece implements Runnable
{
private DatagramSocket ds;
public Rece(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
try
{
while(true)
{
byte[] bu=new byte[1024];
DatagramPacket dp=new DatagramPacket(bu,bu.length);
ds.receive(dp);
String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength());
System.out.println(ip+":"+data);
}
}
catch(Exception e)
{
throw new RuntimeException("");
}
}
}
public class ChatDemo
{
public static void main(String[] args) throws Exception
{
DatagramSocket send=new DatagramSocket();
DatagramSocket rece=new DatagramSocket(10001);
new Thread (new Send(send)).start();
new Thread (new Rece(rece)).start();
}
}
*TCP传输
* Socket和ServerSocket
* 建立客户端和服务器端
* 建立连接后,通过Socket中的IO流进行数据的传输
* 关闭socket
* 同样,客户端与服务器端是两个89独立的应用程序*TCP传输
* Socket和ServerSocket
* 建立客户端和服务器端
* 建立连接后,通过Socket中的IO流进行数据的传输
* 关闭socket
* 同样,客户端与服务器端是两个独立的应用程序
import java.net.*;
import java.io.*;
class TCPClient
{
public static void main(String[] args) throws Exception
{
//创建Socket服务,指定要连接的主机和端口
Socket s=new Socket("127.0.0.1",10000);
//获取服务中的输出流,写数据到数据通道中
OutputStream out=s.getOutputStream();
out.write("数据".getBytes());
s.close();
}
}
class TCPServer
{
public static void main(String[] args) throws Exception
{
//创建ServerSocket服务,监听一个端口
ServerSocket ss=new ServerSocket(10001);
//ServerSocket的accept方法连接客户端
Socket s=ss.accept();
System.out.println(s.getInetAddress().getHostAddress());
//使用客户端对象的读取流读取数据
InputStream in=s.getInputStream();
byte[] bu=new byte[1024];
int len= in.read(bu);
System.out.println(new String(bu,0,len));
s.close();//关闭客户端
}
}
文本转换
/*
* 建立一个文本转换服务器
* 客户端向服务端发送文本,服务端将文本转成大写返回服务端
* 分析:
* 客户端
* 源:键盘录入
* 目的:网络输出流
* 是文本
* 步骤
* 1,建立服务
* 2,获取键盘录入
* 3,写入流
* 4,获取服务端返回大写数据
* 5,关闭资源
import java.net.*;
import java.io.*;
class TransClient
{
public static void main(String[] args) throws Exception
{
//建立服务
Socket s=new Socket("127.0.0.1",10000);
//获取键盘录入
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//写到流中
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//获取流
BufferedReader bri=new BufferedReader(new InputStreamReader(s.getInputStream()));
String line=null;
while((line=br.readLine())!=null)
{
if("over".equals(line))
break;
bw.write(line);
//接收服务端返回的大写
bw.newLine();
bw.flush();
String str=bri.readLine();
System.out.println(str);
}
br.close();
s.close();
}
}
/*
* 服务端
* 源:socket读取流
* 目的:网络输出流
* 是文本
* */
class TransServer
{
public static void main(String[] args) throws Exception
{
//建立服务
ServerSocket ss=new ServerSocket(10000);
//拿到客户端对象
Socket s=ss.accept();
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip);
//建立读取流和写出流
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//操作
String line=null;
while((line=br.readLine())!=null)
{
bw.write(line.toUpperCase());
bw.newLine();//换行,结束标记
bw.flush();
}
s.close();
ss.close();
}
}
/*
* 阻塞式的方法一定要结束标记才行,比如readLine一定要独到换行
* 本练习中可以用PrintWriter 流的println方法写出,直接自带换行,字节自动刷新*/
练习:
上传
import java.io.*;
import java.net.*;
class textClient
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("1922.168.0.100",10000);
BufferedReader br=new BufferedReader(new FileReader("C:\\Users\\dell\\Desktop\\新建文本文档.txt"));
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
BufferedReader br1=new BufferedReader(new InputStreamReader(s.getInputStream()));
String line=null;
while((line=br.readLine())!=null)
{
pw.println(line);
}
String str=br1.readLine();
System.out.println(str);
s.shutdownOutput();
br.close();
pw.close();
s.close();
}
}
class textServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(10000);
Socket s=ss.accept();
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(new FileWriter("C:\\Users\\dell\\Desktop\\新建文本文档.txt"),true);
PrintWriter pw1=new PrintWriter(s.getOutputStream(),true);
String line =null;
while((line=br.readLine())!=null)
{
pw.println(line);
}
pw1.write("上传成功");
br.close();
s.close();
ss.close();
}
}
多线程上传
步骤是固定的,是代码和功能的逐渐丰富。
import java.io.*;
import java.net.*;
class Client
{
public static void main(String[] args) throws Exception
{
if(args.length!=1)
{
System.out.println("选择文件");
return;
}
File file=new File(args[0]);
Socket s=new Socket("127.0.0.1",10001);
FileInputStream fis=new FileInputStream(file);
OutputStream out=s.getOutputStream();
byte[] bu=new byte[1024];
int len=0;
while((len=fis.read(bu))!=-1)
{
out.write(bu, 0, len);
}
s.shutdownOutput();
//接受服务端返回数据
InputStream in=s.getInputStream();
byte[] b=new byte[1024];
int len1=in.read(b);
System.out.println(new String(b,0,len1));
fis.close();
s.close();
}
}
//服务端多线程封装
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");
InputStream in=s.getInputStream();
File file=new File(ip+count+".jpg");
while(file.exists())
file=new File(ip+(count++)+".jpg");
FileOutputStream fos=new FileOutputStream(file);
byte[] b=new byte[1024];
int len=0;
while((len=in.read(b))!=-1)
{
fos.write(b, 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(10001);
while(true)
{
Socket s=ss.accept();
new Thread(new PicThread(s)).start();
}
}
}
登录Demo
import java.io.*;
import java.net.*;
class User
{
public static void main(String[] args) throws Exception
{
//建立服务
Socket s=new Socket("127.0.0.1",10000);
//获取键盘录入
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//写到流中
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
//获取流
BufferedReader bri=new BufferedReader(new InputStreamReader(s.getInputStream()));
for(int x=0;x<3;x++)
{
String line=br.readLine();
if(line==null)
break;
pw.println(line);
//接收服务端返回的数据
String str=bri.readLine();
System.out.println(str);
if(str.contains("欢迎"));
break;
}
br.close();
s.close();
}
}
class UserThread implements Runnable
{
private Socket s;
UserThread(Socket s)
{
this.s=s;
}
public void run()
{
try
{
for(int x=0;x<3;x++)
{
BufferedReader bri=new BufferedReader(new InputStreamReader(s.getInputStream()));
String name=bri.readLine();
if(name==null)
break;
BufferedReader br=new BufferedReader(new FileReader("user.txt"));
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
String line=null;
boolean flag=false;
while((line=br.readLine())!=null)
{
if(line.equals(name))
{
flag=true;
break;
}
}
if(flag)
{
System.out.println(name+"已登录");
pw.println("欢迎光临");
break;
}
else
{
System.out.println(name+"尝试登录");
pw.println("用户名不存在");
}
}
s.close();
}
catch(Exception e)
{
throw new RuntimeException("");
}
}
}
class loginServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(10001);
while(true)
{
Socket s=ss.accept();
new Thread(new UserThread(s)).start();
}
}
}
URL:
import java.net.*;
class URLDemo
{
public static void main(String[] args) throws MalformedURLException
{
URL url=new URL("http://www.baidu.com/index.php?tn=10018802_hao");
//方法们
sop(url.getProtocol());//获取协议
sop(url.getHost());//获取主机
sop(url.getPort());//获取端口
sop(url.getPath());//获取路径部分
sop(url.getFile());//获取文件
sop(url.getQuery());//获取查询部
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
import java.io.*;
import java.net.*;
public class URLConnectionDemo
{
public static void main(String[] args) throws IOException
{
URL url=new URL("http://www.baidu.com/index.php?tn=10018802_hao");
URLConnection con=url.openConnection();
sop(con);
//获取数据
InputStream in=con.getInputStream();
byte[] b=new byte[1024];
int len=in.read(b);
sop(new String(b,0,len));
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
图为访问主机步骤