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

java的网络编程

2014-01-07 20:19 323 查看
网络通信原理:

IP地址是唯一标示网络中一台联网设备(计算机等)的网络地址,有IPv4与IPv6之分。

本地回环地址是127.0.0.1,代表当前计算机本身。

网络通信的对象一般是计算机中的应用程序。端口一般用来标示计算机中的某一个应用程序。

端口是在0~65535取值范围内的,0~1024是公认端口,一般被系统所保留。

常见的公用端口有:

应用程序

    FTP   

  TELNET 

  SMTP   

  DNS   

  HTTP   

  TomCat  

端口号

    21   

  23    

  25   

  53    

  80     

  8080   

当前的网络通信协议有两大类:UDP与TCP协议

UDP用户数据报协议的特点:

(1)UDP是面向无连接的,即发送数据之前不需要建立连接

(2)UDP尽最大努力交付,即连接是不可靠的

(3)UDP是面向报文的

(4)可以一对多通信

UDP对于那些像实时视频等要求实时性高,数据允许有一定误差的应用实用性很高。

Java语言使用UDP进行通信一般需要这几个步骤:

1,建立DatagramSocket服务。

2,提供数据,并将数据封装到数据包中。

3,通过socket服务的发送功能,将数据包发出去。

4,关闭资源。

DatagramPacket数据报包用来实现无连接包投递服务。每条报文仅根据该包中包含的信息从一台机器路由到另一台机器。

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

class UdpSend
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();

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

String line = null;

while((line=bufr.readLine()) != null)
{
if("over".equals(line))
break;

byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.217.1"),10000);

ds.send(dp);
}
ds.close();
}
}

class UdpRece
{
public static void main(String[] args) throws Exception
{
//1.创建udp socket
DatagramSocket ds = new DatagramSocket(10000);
while(true)
{
//2.定义数据包
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);

//3.receive
ds.receive(dp);

//4.取出数据
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
int port = dp.getPort();
System.out.println(ip+"::"+data+"::"+port);
}

//5.关闭资源
//ds.close();
}
}


下面是一个使用UDP进行上传图片的操作:

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

class PicClient
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.217.1",10008);

BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("044.jpg"));

BufferedOutputStream bufOut = new BufferedOutputStream(s.getOutputStream());
byte[] buf = new byte[1024];
int len = 0;
while((len=bufis.read(buf)) != -1)
{
bufOut.write(buf,0,len);
}
s.shutdownOutput();

BufferedInputStream bufIn = new BufferedInputStream(s.getInputStream());

int num = bufIn.read(buf);
System.out.println(new String(buf,0,num));

bufis.close();
s.close();
}
}

/*
只能单线程连接客户端
*/
class PicServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10008);

Socket s = ss.accept();
System.out.println(ip+"...connected");
InputStream in = s.getInputStream();

FileOutputStream fos = new FileOutputStream("001.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();
new Thread(new PicThread(s)).start();
ss.close();
}
}


下面来说TCP协议:

TCP是传输控制协议的简写,TCP有以下几个特点:

(1)TCP是面向连接的传输协议

(2)提供可靠服务

(3)面向字节流

(4)具有检错容错机制

TCP应用于那些对数据完整性要求高的应用,比如,文件传输等。

建立TCP连接的思路:

客户端需要明确服务器的ip 地址以及端口,这样才可以去试着建立连接,如果连接失败,会出现异常。

 

连接成功,说明客户端与服务端建立了通道,那么通过IO流就可以进行数据的传输,而Socket对象已经提供了输入流和输出流象,通过getInputStream(),getOutputStream()获取即可。

 

与服务端通讯结束后,关闭Socket。

这就是一个服务端与客户端进行通信的示例:

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

/*
tcp传输

客户端对应的对象是Socket
服务器端是ServerSocket
*/
class TcpClient2
{
public static void main(String[] args) throws IOException
{
Socket s = new Socket("192.168.217.1",10004);

OutputStream out = s.getOutputStream();
out.write("服务器你好".getBytes());

InputStream in = s.getInputStream();

byte[] buf = new byte[1024];

int len = in.read(buf);

System.out.println(new String(buf,0,len));
s.close();
}
}

/*
服务器:
1.建立服务器的soclet服务 ServerSocket() 并监听一个端口
2.获取连接过来的客户端对象 accept
3.客户端发来数据,服务器使用相应的客户端对象,并获取和该客户端对象的读取流来读取发过来的数据

*/
class TcpSever2
{
public static void main(String[] args) throws IOException
{
ServerSocket ss = new ServerSocket(10004);

Socket s = ss.accept();

String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"...connected");
InputStream in = s.getInputStream();

byte[] buf =new byte[1024];

int len = in.read(buf);

System.out.println(new String(buf,0,len));

OutputStream out = s.getOutputStream();

out.write("你也好".getBytes());

s.close();
ss.close();
}
}


下面是一个多线程客户端通过TCP连接服务器,上传图片的示例:

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

class PicClient
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.217.1",10008);

BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("044.jpg"));

BufferedOutputStream bufOut = new BufferedOutputStream(s.getOutputStream());
byte[] buf = new byte[1024];
int len = 0;
while((len=bufis.read(buf)) != -1)
{
bufOut.write(buf,0,len);
}
s.shutdownOutput();

BufferedInputStream bufIn = new BufferedInputStream(s.getInputStream());

int num = bufIn.read(buf);
System.out.println(new String(buf,0,num));

bufis.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+"...connected");
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[] 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 (IOException e)
{
throw new RuntimeException(ip+"上传失败");
}

}
}
class PicServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10008);
while(true)
{
Socket s = ss.accept();
new Thread(new PicThread(s)).start();
}
//ss.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: