Java 网络编程
Java 网络编程
TCP
客户端
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/**
* 客户端
*/
public class TcpClient {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
socket = new Socket(serverIP, port);
// 发送消息
os = socket.getOutputStream();
os.write("你好!".getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null)
{
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null)
{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
服务端
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务端
*/
public class TcpServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket accept = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
serverSocket = new ServerSocket(9999);
while (true)
{
// 等待客户端连接
accept = serverSocket.accept();
// 读取客户端的消息
is = accept.getInputStream();
// 管道流
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read()) != -1)
{
baos.write(buffer, 0, len);
}
System.out.println(baos.toString());
}
/*byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1)
{
String msg = new String(buffer, 0, len);
System.out.println(msg);
}*/
} catch (Exception e)
{
e.printStackTrace();
} finally {
// 关闭流 先开后关
if (baos != null)
{
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null)
{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (accept != null)
{
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null)
{
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
TCP 文件上传
客户端 —— 上传文件
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
/**
* 上传文件
*/
public class TcpClient {
public static void main(String[] args) throws IOException {
// 创建一个socket连接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
// 创建一个输出流
OutputStream os = socket.getOutputStream();
// 文件流
FileInputStream fis = new FileInputStream(new File("xxxx.jpg"));
// 写出文件
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read()) != -1)
{
os.write(buffer, 0, len);
}
// 通知服务器,上传完毕
socket.shutdownOutput();
// 确定服务器接收完毕才能够断开连接
InputStream is = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
if ((len2 = is.read(buffer)) != -1)
{
baos.write(buffer2, 0, len2);
}
System.out.println(baos.toString());
// 关闭资源
baos.close();
is.close();
fis.close();
os.close();
socket.close();
}
}
服务端 —— 接收文件
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 接收文件
*/
public class TcpServer {
public static void main(String[] args) throws IOException {
// 创建服务
ServerSocket serverSocket = new ServerSocket(9000);
// 监听客户端
Socket socket = serverSocket.accept(); // 阻塞式监听,会一直等待客户端连接
// 获取输入流
InputStream is = socket.getInputStream();
// 文件输出
FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1)
{
fos.write(buffer, 0, len);
}
// 通知客户端接收完毕
OutputStream os = socket.getOutputStream();
os.write("文件接收完毕!".getBytes());
// 关闭资源
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
UDP
客户端
import java.io.IOException;
import java.net.*;
// 不需要连接服务端
public class UdpClient {
public static void main(String[] args) throws IOException {
// 建立一个socket
DatagramSocket socket = new DatagramSocket();
// 建包
String msg = "你好,服务器!";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9000;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
// 发包
socket.send(packet);
// 关闭资源
socket.close();
}
}
服务端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
// 还要等待客户端的连接
public class UdpServer {
public static void main(String[] args) throws IOException {
// 开放端口
DatagramSocket socket = new DatagramSocket(9000);
// 接收数据
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);// 接收
socket.receive(packet);
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(), 0, packet.getLength()));
// 关闭连接
socket.close();
}
}
UDP 聊天实现
发送方
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class UdpSender {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true)
{
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));
socket.send(packet);
if ("bye".equals(data))
{
break;
}
}
socket.close();
}
}
接收方
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceive {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(6666);
while (true)
{
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet); // 阻塞式接收包裹
// 断开连接
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(receiveData);
if ("bye".equals(receiveData))
{
break;
}
}
socket.close();
}
}
UDP 多线程在线咨询
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class TalkSend implements Runnable {
DatagramSocket socket = null;
BufferedReader reader = null;
private int fromPort;
private String toIP;
private int toPort;
public TalkSend(int fromPort, String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try {
socket = new DatagramSocket(fromPort);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true)
{
try {
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(toIP, toPort));
socket.send(packet);
if ("bye".equals(data))
{
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReceive implements Runnable {
DatagramSocket socket = null;
private int port;
private String msgFrom;
public TalkReceive(int port, String msgFrom) {
this.port = port;
this.msgFrom = msgFrom;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet); // 阻塞式接收包裹
// 断开连接
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(msgFrom + ":" + receiveData);
if ("bye".equals(receiveData)) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
public class TalkStudent {
public static void main(String[] args) {
// 开启两个线程
new Thread(new TalkSend(7777, "localhost", 9999)).start();
new Thread(new TalkReceive(8888, "老师")).start();
}
}
public class TalkTeacher {
public static void main(String[] args) {
// 开启两个线程
new Thread(new TalkSend(5555, "localhost", 8888)).start();
new Thread(new TalkReceive(9999, "学生")).start();
}
}
URL 下载网络资源
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class URL_Download {
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=tkzc&password=123456");
System.out.println(url.getProtocol()); // 协议名
System.out.println(url.getHost()); // 主机
System.out.println(url.getPort()); // 端口
System.out.println(url.getPath()); // 地址
System.out.println(url.getFile()); // 文件
System.out.println(url.getQuery()); // 查询字符
// 连接资源
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("xxxx.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1)
{
fos.write(buffer, 0, len);
}
fos.close();
is.close();
urlConnection.disconnect(); // 断开连接
}
}

浙公网安备 33010602011771号