Java必学必会之网络编程攻略
一、网络基础概念
1.1 OSI七层模型
OSI七层模型是一种通用的网络协议分层模型,分为七层。自下而上分别为:物理层、数据链路层、网络层、传输层、会话层、表示层、应用层。
Java通常使用的是传输层到应用层。
1.2 TCP/IP协议
TCP/IP协议比OSI七层模型更常用。分为四层:网络接口层、网络层、传输层、应用层。
Java提供了Socket和ServerSocket两个类用于支持TCP/IP协议的网络编程。
二、Socket编程
2.1 Socket的基础
Socket是Java提供的用于实现TCP/IP协议的基础类。
客户端通过Socket连接服务端创建Socket,服务端通过调用accept()方法接受客户端的Socket连接。
示例1:客户端代码
String hostName = "localhost";
int portNumber = 5555;
try (
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
示例2:服务端代码
int portNumber = 5555;
try (
ServerSocket serverSocket =
new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
// Initiate conversation with client
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
2.2 Socket的高级应用
通过设置Socket的一系列参数,可以实现Socket编程的更高级应用,如服务端与多个客户端同时通信、非阻塞式通信等。
示例3:服务端同时与多个客户端通信的代码
public class MultiServer implements Runnable {
private Socket socket;
private ArrayList<Socket> socketList = new ArrayList<Socket>(); // 客户端List
public MultiServer(Socket socket, ArrayList<Socket> socketList) {
this.socket = socket;
this.socketList = socketList;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Message Received: " + inputLine);
// 向其它客户端发送消息
for (Socket eachSocket : socketList) {
if (eachSocket != socket) {
OutputStream outToClient = eachSocket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToClient);
out.writeUTF(inputLine);
}
}
}
// 关闭连接
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class MultiServerMain {
public static void main(String[] args) throws IOException {
int portNumber = 5555;
ArrayList<Socket> socketList = new ArrayList<Socket>();
ServerSocket serverSocket = new ServerSocket(portNumber);
while (true) {
Socket socket = serverSocket.accept();
socketList.add(socket);
new Thread(new MultiServer(socket, socketList)).start();
}
}
}
三、总结
本篇攻略详细介绍了Java必学必会之网络编程,包括网络基础概念、Socket编程的基础和高级应用等内容,并给出了多个示例说明。掌握这些知识,可以帮助Java开发者更好地进行网络编程。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java必学必会之网络编程 - Python技术站