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

黑马程序员——Java网络编程

2011-12-23 20:20 381 查看
黑马程序员——Java网络编程
----------------------
android培训、java培训、期待与您交流! ----------------------
一、TCP和UDP

● UDP

■ 将数据的源和目的封装在数据包中,不需要建立连接

■ 第个数据报的大小限制在64K内

■ 因无连接,是不可靠的协议,速度快

● TCP

■ 建立连接,开成传输数据的通道;

■ 在连接中进行大数据量传输;

■ 通过三次握手完成连接,是可靠协议;

■ 必须建立连接,效率会稍低

二、Socket

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

● 通信的两端都有Socket

● 网络通信其实就是Socket间的通信

● 数据在两个Socket间通过IO传输

三、UDP传输

● UDP通信流程:

1、建立UDPSocket服务通过DatagramSocket对象

2、提供数据,并将数据封装到数据包中(DatagramPacket(byte[] buf,int length,InetAddress address,int port))

3、通过Socket服务的发送功能,将数据发送出去通过send()方法

4、关闭资源,close()方法。

● 实例:UDP简单通信实例

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

// 接收端
public class UdpReceive {
public static void main(String[] args) throws IOException {
DatagramSocket s = new DatagramSocket(9999);

byte[] buf = new byte[1024];
DatagramPacket p = new DatagramPacket(buf, buf.length);

s.receive(p);

String ip = p.getAddress().getHostAddress();
String data = new String(p.getData(), 0, p.getLength());
int port = p.getPort();

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

s.close();
}
}


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

// 发送端
public class UdpSend {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();

byte[] data = "Helloworld".getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length,
InetAddress.getByName("localhost"), 9999);

socket.send(packet);

socket.close();
}
}

● 实例:UDP简单通信实例(方式二)

发送端

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

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

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;

while ((line = br.readLine()) != null) {
byte[] b = line.getBytes();

DatagramPacket p = new DatagramPacket(b, 0, b.length,
InetAddress.getByName("localhost"), 8989);

s.send(p);

if ("88".equals(line))
break;
}

br.close();
s.close();
}
}

接收端

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpReceive2 {
public static void main(String[] args) throws Exception {
DatagramSocket s = new DatagramSocket(8989);

byte[] b = new byte[1024 * 64];
DatagramPacket p = new DatagramPacket(b, b.length);

while (true) {
s.receive(p);

String ip = p.getAddress().getHostAddress();
String data = new String(p.getData(), 0, p.getLength());

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

if("88".equals(data))
break;
}

s.close();
}
}

● 实例:简单UDP聊天实例

// Send.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Send extends Thread {
private DatagramSocket s;

@Override
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String line = null;

try {
while ((line = br.readLine()) != null) {
byte[] buf = line.getBytes();

DatagramPacket p = new DatagramPacket(buf, buf.length,
InetAddress.getByName("10.11.24.255"), 10000);

s.send(p);

if ("88".equals(line))
break;
}

br.close();
} catch (IOException e) {
throw new RuntimeException("发送失败");
}
}

public Send(DatagramSocket s) {
super();
this.s = s;
}
}


// Receive.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Receive extends Thread {
private DatagramSocket s;

@Override
public void run() {
try {
byte[] buf = new byte[1024 * 64];
DatagramPacket p = new DatagramPacket(buf, buf.length);

while (true) {
s.receive(p);

String ip = p.getAddress().getHostAddress();
String data = new String(p.getData(), 0, p.getLength());

System.out.println("【" + ip + "】说: " + data);
}
} catch (Exception e) {
throw new RuntimeException("接收失败");
}
}

public Receive(DatagramSocket s) {
super();
this.s = s;
}
}


// ChatDemo.java
import java.net.DatagramSocket;

public class ChatDemo {
public static void main(String[] args) throws Exception {
DatagramSocket sendSocket=new DatagramSocket();
DatagramSocket receSocket=new DatagramSocket(10000);

new Send(sendSocket).start();
new Receive(receSocket).start();
}
}
三、TCP传输

TCP分客户端和服务端,客户端对应的对象是Socket,服务端对应的对象是ServerSocket。

● 实例:演示Tcp传输的客户端与服务端的互访

服务端

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer2 {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10000);

Socket s = ss.accept();

String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + "connected...  says: ");

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();
}
}
客户端

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClient2 {
public static void main(String[] args) throws Exception {
Socket s = new Socket(InetAddress.getByName("localhost"), 10000);

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();
}
}
● 实例:TCP文件传输

服务端

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

public class FileUploadServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10002);

Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + "connected success...");

BufferedReader br = new BufferedReader(new InputStreamReader(
s.getInputStream()));
String filename = br.readLine(); // 接收文件名
System.out.println("文件名:" + filename);

BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("d:\\upload\\" + filename));

byte[] b = new byte[1024 * 64];
int len = 0;

while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
bos.flush();
}

PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println("文件【" + filename + "】传输成功!");

s.close();
ss.close();
}
}
客户端

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

public class FileUploadClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket(InetAddress.getByName("10.11.24.235"), 10002);

// 要发送的文件
File file = new File("d:\\卷面成绩查询.exe");

if (!file.exists()) {
System.err.println("文件不存在!");
s.close();
return;
}

// 发送文件名到服务器
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(file.getName());

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
byte[] b = new byte[1024 * 64];
int len = 0;

while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
bos.flush();
}

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

BufferedReader br = new BufferedReader(new InputStreamReader(
s.getInputStream()));
String str = br.readLine();
System.out.println(str);

s.close();
}
}


----------------------
android培训、java培训、期待与您交流! ----------------------
详细请查看:http://edu.csdn.net/heima
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: