您的位置:首页 > 理论基础 > 计算机网络

java笔记-网络编程-网络基础

2014-08-16 10:21 441 查看
网络编程
网络通信的基础:

1.找到对方IP

2.将数据发送到对方指定的应用程序上,该应用程序需要有一个端口被发送的数据识别。

3.定义通信规则,该规则称为协议。

网络参考模型



网络传输协议(UDP,TCP/IP)

UDP

1.将数据,源和目的封装成到数据包中,不需要连接;

2.每个数据包的大小限制在64k内;

3.因无连接,是不可靠协议;

4.不需要建立建立,传输速度快。

TCP/IP

1.需要建立连接,形成数据传输的通道;

2.在连接中可进行大量的数据传输;

3.通过三次握手连接,是可靠的通信协议;

4.必须建立连接,效率会慢。

网络通信机制Socket

Socket就是为网络服务提供的一种机制,通信的两端都有Socket,网络通信其实就是Socket间的通信,数据在两个Socket间通过IO传输。

Socket发送端

思路:

1.建立UDPSocket服务;

2.将发送的数据存储在数据包中;

3.通过Socket服务的发送功能将数据发送出去;

4.关闭资源。

import java.net.*;
class SocketSendDemo
{
public static void main(String[] args) throws Exception
{
//构建数据包;
DatagramSocket ds=new DatagramSocket();
//定义要发送的数据并存储在字节数组中。
byte[] buf="Socket send data.".getBytes();;
//打包要发送的数据;
DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("localhost"),1004);
//发送打包的数据。
ds.send(dp);
//关闭资源。
ds.close();
}
}
Socket接收端

思路:

1.定义UDPSocket服务,通常会监听一个端口,其实就是给这个接收网络应用程序定义数字标识,方便识别哪些应用程序可以通过该端口处理数据;

2.定义数据包,存储接收到的数据,通过数据包对象可以更方便的提取包中的不同数据信息;

3.通过Socket服务的receive方法接收发送的数据并存储在定义好的数据包中;

4.通过数据包对像的特有功能,将不同的数据取出并打印在控制台上;

5.关闭资源。

import java.net.*;
class UdpReceive
{
public static void main(String[] args) throws Exception
{
//构建数据包;并定义该接收端的端口为1004
DatagramSocket ds=new DatagramSocket(1004);
//构建字节数组存储要发送的数据
byte[] buf=new byte[1024];
//打包要接收长度为buf.length的数据
DatagramPacket dp=new DatagramPacket(buf,buf.length);
//接收发送的数据的数据。该语句会一直等待接收发送端发送过来的数据
ds.receive(dp);
//根据接收到的包的对象获取相关信息。
//getAddress返回InetAddress对象,该对象的getHostAddress方法返回主机ip地址的字符串。
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();
}
}
发送键盘录入的数据

思路:

1.构建socket发送端

2.接收键盘录入的信息,以行为单位,按照字节存储

3.将存储后的字节数据打包发送给接收端

4.构建socket接收端

5.循环接收发送端发送的数据

6.根据发送的数据包对象分拆数据信息并打印。

/*
** 发送键盘录入的数据。
*/
import java.io.*;
import java.net.*;
class KeySend
{
public static void main(String[] args) throws Exception
{
//构建socket服务
DatagramSocket ds=new DatagramSocket();
//接收键盘数据
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
String line;
//循环读取键盘输入。
while((line=bufr.readLine())!=null){
//设置中止输入符
if("886".equals(line)){
break;
}
//将行数据转化为字节数据
byte[] buf=line.getBytes();
//构建socket包,打包要发送的数据
//localhost若更改为192.168.1.255,为广播。
DatagramPacket dp=new DatagramPacket(buf,0,buf.length,InetAddress.getByName("localhost"),10004);
ds.send(dp);
}
ds.close();
}
}
class KeyReceive
{
public static void main(String[] args) throws Exception
{
//构建socket服务,接收发送给10004端口的数据。
DatagramSocket ds=new DatagramSocket(10004);
//循环接收数据。
while(true){
//存储接受到的数据。
byte[] bufr=new byte[1024];
//将接收到的数据打包。
DatagramPacket dp=new DatagramPacket(bufr,bufr.length);
ds.receive(dp);
//根据接收到的数据对象,逐项分析数据中的内容。
String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength());
int port =dp.getPort();
System.out.println(ip+"::"+port+"::"+data);
}
//ds.close();
}
}
聊天程序

聊天分为发送和接收两部分,建立两个线程分别启动发送和接收线程即可。

1.构建发送线程

2.不断读取键盘输入信息,按行打包数据

3.将打包的数据发送到接收端

4.异常捕捉

5.构建接收线程

6.建立字节数组,接收发送过来的数据并存储在字节数组中

7.打包接收到的字节数组,建立包对象

8.根据包对象分拆包数据信息并打印

9.异常捕捉

10.启动发送和接收线程。

import java.io.*;
import java.net.*;
/*
** 发送
*/
class Send implements Runnable
{
private DatagramSocket ds;
Send(DatagramSocket ds){
this.ds=ds;
}
public void run(){
try{
//读取键盘输入
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
String line=null;
//循环读取行信息。
while((line=bufr.readLine())!=null){
//输入886停止程序
if("886".equals(line)){
break;
}
byte[] buf=new byte[1024];
buf=line.getBytes();
//将要发送的数据打包并发送,指定要发送的ip地址和端口
DatagramPacket dp=new DatagramPacket(buf,0,buf.length,InetAddress.getByName("localhost"),10009);
ds.send(dp);
}
//关闭资源。
ds.close();
}
catch(Exception e){
throw new RuntimeException("send error.");
}
}
}
/*
** 接收
*/
class Receive implements Runnable
{
private DatagramSocket ds;
Receive(DatagramSocket ds){
this.ds=ds;
}
public void run(){
try{
//不断读取发送过来的信息
while(true){
byte[] buf=new byte[1024];
//打包接收的数据信息。
DatagramPacket dp=new DatagramPacket(buf,buf.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("receive error.");
}
}
}
class ChatDemo
{
public static void main(String[] args) throws Exception
{
//建立发送socket服务。
DatagramSocket sendInfo=new DatagramSocket();
//建立接收socket服务,并初始化接收端口
DatagramSocket receiveInfo=new DatagramSocket(10009);
//开启发送和接收线程。
new Thread(new Receive(receiveInfo)).start();
new Thread(new Send(sendInfo)).start();
}
}


TCP协议数据传输

客户端:

1.建立socket服务,指定要连接的主机和端口

2.获取socket的输出流,将数据写入到输出流,通过网络发送给服务器

3.获取socket的输入流,获取服务器端的反馈信息并打印

4.关闭客户端资源

服务端:

1.建立SeverSocket服务,监听连接到服务器的端口

2.获取连接到服务器的客户端对象

3.根据客户端对象获取输入流,读取客户端发送数据并打印

4.接收到数据后,再获取输出流,向输出流发送反馈信息

/*
** 需求:客户端向服务器端发送数据,服务器端接收数据后打印到控制台
*/
import java.io.*;
import java.net.*;
class TcpClient
{
public static void main(String[] args) throws Exception
{
/*
** 客户端发送数据
*/
//建立socket对象,该对象一旦建立,即和服务端建立了连接。
Socket s=new Socket("localhost",10000);
//通过socket对像方法获取输出流。
OutputStream os=s.getOutputStream();
//将数据写入到输出流
os.write("client send:hello cs.".getBytes());
/*
** 接收服务端发送的数据
*/
InputStream in=s.getInputStream();
byte[] buf=new byte[1024];
int len=0;
//读取客户端输入流中的数据
len=in.read(buf);
System.out.println(new String(buf,0,len));
s.close();
}
}
class TcpServer
{
public static void main(String[] args)throws Exception{
/*
** 服务器接收客户端发送的数据
*/
//建立serverSocket服务端并监听10000端口
ServerSocket ss=new ServerSocket(10000);
//通过serverSocket对象方法获取连接到该服务器的客户端。
Socket s=ss.accept();
//通过连接的客户端获取输入流。
InputStream is=s.getInputStream();
byte[] buf=new byte[1024];
int len=0;
//读取输入流中的数据。
len=is.read(buf);
//根据客户端对象获取连接的客户端的ip地址。
String ip=s.getInetAddress().getHostAddress();
//打印输出。
System.out.println(ip+":"+new String(buf,0,len));
/*
** 服务器端接收到数据后发送反馈信息。
*/
OutputStream os=s.getOutputStream();
os.write("sever send:I have receive data.".getBytes());
}
}
客户端服务端交互(使用缓存技术)

/*
** 需求:建立文本转换服务器
** 客户端给服务端发送文本,服务端将文本转换为大写再发送给客户端
** 客户端可不断输入进行文本转换,但输入over时退出。
*/
import java.io.*;
import java.net.*;
class TransClient
{
public static void main(String[] args) throws Exception
{
//建立socket服务,初始化主机连接和端口
Socket s=new Socket("localhost",10001);
/*
** 向服务端发送键盘录入数据
*/
//建立缓存,由于客户端和服务端传送的是字节数据,缓存使用的是字符数据,需要进行字节到字符的转换。
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
String len=null;
while((len=bufr.readLine())!=null){
if("over".equals(len)){
break;
}
bufw.write(len);
//bufr.readLine()在读取数据时没有读取换行。需要在行数据后面添加换行。
bufw.newLine();
bufw.flush();

/*
** 接收服务器端返回的大写数据,并打印。
*/
String receUper=bufIn.readLine();
System.out.println(receUper);
}
bufr.close();
s.close();
}
}
class TransServer
{
public static void main(String[] args)throws Exception{
/*
** 建立服务器端和客户端的连接
*/
//建立服务器,监听端口10001
ServerSocket ss=new ServerSocket(10001);
//获取连接到服务器的客户端。
Socket s=ss.accept();
//获取客户端ip
String ip=s.getInetAddress().getHostAddress();
//一旦连接到客户端即输出连接成功信息。
System.out.println(ip+"...connected.");
/*
** 接收客户端的数据并转化为大写
*/
//建立缓存,由于客户端和服务端传送的是字节数据,缓存使用的是字符数据,需要进行字节到字符的转换。
BufferedReader bufr=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String len=null;
//readLine以换行为结束标识。
while((len=bufr.readLine())!=null){
System.out.println("client:"+len);
String uper=len.toUpperCase();
/*
** 向服务端发送键盘录入数据
*/
bufw.write(uper);
bufw.newLine();
bufw.flush();
}
s.close();
//由于客户端的连接是建立在服务端的基础上,服务端一旦断开,客户端也将断开连接。
ss.close();
}
}
保存客户端发送服务器的文本文件(上传文件)

import java.io.*;
import java.net.*;
class TextClient
{
public static void main(String[] args) throws Exception
{
/*
** 建立客户端,并初始化连接主机和端口
*/
Socket s=new Socket("localhost",10011);
/*
** 建立缓存,读取文本
*/
//将文本信息放入缓存。
BufferedReader bufr=new BufferedReader(new FileReader("KeyDemo.java"));
//将数据打印到输出流,并自动刷新(true)缓存
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
String line=null;
while((line=bufr.readLine())!=null){
//该打印附带换行。
pw.println(line);
}
//此套接字的输入流至于流的末尾(文本结束标识)
s.shutdownOutput();
//读取输入流信息并打印
BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
String uploadOk=bufIn.readLine();
System.out.println(uploadOk);
//关闭资源。
bufr.close();
s.close();
}
}
class TextServer
{
public static void main(String[] args)throws Exception{
/*
** 建立服务器端,并监听端口10011
*/
ServerSocket ss=new ServerSocket(10011);
//获取连接到服务器的客户端。
Socket s=ss.accept();
//倘或连接成功则获取ip地址并打印。
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip);
//构建输入流缓存。
BufferedReader bufr=new BufferedReader(new InputStreamReader(s.getInputStream()));
//将文本数据写入server.txt并自动刷新。
PrintWriter printw=new PrintWriter(new FileWriter("server.txt"),true);
String line=null;
while((line=bufr.readLine())!=null){
//附带换行信息。
printw.println(line);
}
//将客户端发送的数据写入指定文件后反馈上传成功信息,该信息打印到socket的输出流。
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
pw.println("上传成功。");
//关闭资源。
bufr.close();
s.close();
ss.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: