如今大部分的编程开发都离不开网络,Java IO同样可以基于网络进行开发。事实上网络编程可以看做两个进程之间的通信,我们可以通过java对网络的支持,建立两点的网络连接,连接建立成功之后,就可以看做是本地的文件操作了。前面对于文件进行的类似操作也可以适用在这里。
我们常用的有TCP/UDP建立连接,下面将分别举例说明:
TCPClient:
package NetIo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TCPClient {
private Socket socket;
private boolean connectFlag;
private InputStream is;
private OutputStream os;
private byte[] buffer = new byte[1024];
public static void main(String[] args) {
TCPClient client = new TCPClient();
if (client.initSocket()) {
client.execute();
} else {
System.out.println("the connect has some wrong.");
}
}
private boolean initSocket() {
try {
socket = new Socket("127.0.0.1", 5008);
socket.setSoTimeout(2000);
connectFlag = true;
} catch (IOException e) {
e.printStackTrace();
}
return connectFlag;
}
private void execute() {
String message = "Hello World!";
try {
is = socket.getInputStream();
os = socket.getOutputStream();
int len;
os.write(message.getBytes());
while (true) {
len = is.read(buffer);
if (len != -1) {
String response = new String(buffer, 0, len);
System.out.println("从服务器接收的消息为" + response);
break;
}
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
TCPServer:
package NetIo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer implements Runnable{
private ServerSocket serversocket;
private Socket socket;
private boolean connectFlag;
private InputStream is;
private OutputStream os;
private byte[] buffer = new byte[1024];
public TCPServer(){
}
public TCPServer(Socket socket){
this.socket = socket;
}
public static void main(String[] args) {
TCPServer server = new TCPServer();
if(server.initServer()){
server.execute();
}else {
System.out.println("there are some mistakes when connect");
}
}
private boolean initServer(){
try {
serversocket = new ServerSocket(5008);
connectFlag = true;
} catch (IOException e) {
e.printStackTrace();
}
return connectFlag;
}
private void execute(){
while(true){
try {
socket = serversocket.accept();
new Thread(new TCPServer(socket)).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
try {
String host = socket.getInetAddress().toString();
int port = socket.getPort();
os = socket.getOutputStream();
is = socket.getInputStream();
while(true){
if(socket.isClosed()){
return;
}
int len = is.read(buffer);
if(len != -1){
System.out.println("从地址为"+host+"端口为"+port+"的客户端发来消息:"+new String(buffer,0,len));
os.write("服务器已接收消息成功".getBytes());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
先执行服务端,在执行客户端代码,可以在控制台看到如下打印:
下面将举例说明基于UDP的网络IO。
UDPClient:
package NetIo;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPClient {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
String message = "Hello World!";
byte[] buffer = message.getBytes();
InetAddress address = InetAddress.getByName("127.0.0.1");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length,
address, 5000);
socket.send(packet);
while (true) {
byte[] buf = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
socket.receive(receivePacket);
String response = new String(receivePacket.getData(), 0,
receivePacket.getData().length);
if (response != null) {
System.out.println("从服务端成功接收消息:" + response);
socket.close();
break;
}
}
}
}
UDPServer:
package NetIo;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.concurrent.atomic.AtomicInteger;
public class UDPServer implements Runnable {
private DatagramSocket socket;
private DatagramPacket packet;
public UDPServer(DatagramSocket socket, DatagramPacket packet) {
this.socket = socket;
this.packet = packet;
}
public static void main(String[] args) throws IOException {
AtomicInteger numThreads = new AtomicInteger(0);
DatagramSocket socket = new DatagramSocket(5000);
while (true) {
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
Thread thread = new Thread(new UDPServer(socket, packet));
thread.start();
numThreads.incrementAndGet();
}
}
@Override
public void run() {
String message = new String(packet.getData(), 0,
packet.getData().length);
int port = packet.getPort();
InetAddress address = packet.getAddress();
System.out.println("get a message from address:" + address + " port:"
+ port + " message:" + message);
String respose = "服务器已成功收到消息";
DatagramPacket resPacket = new DatagramPacket(respose.getBytes(),
respose.getBytes().length, address, port);
try {
socket.send(resPacket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
先执行服务端,在执行客户端代码,可以在控制台看到如下打印:
上面的两个例子模拟了UDP简单通信。