### 基於TCP協議的網絡編程 TCP 是面向鏈接的運輸層協議,比較複雜,應用程序在使用 TCP 協議以前必須先創建鏈接,才能傳輸數據,數據傳輸完畢以後須要釋放已經創建的鏈接。 TCP 的優勢是很是可靠,經過 TCP 傳輸的數據,不會出現數據丟失的狀況,而且數據是按照前後順序依次到達的,缺點是速度慢,效率低。 ```java import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; OutputStream outputStream = null; InputStream inputStream = null; DataInputStream dataInputStream = null; DataOutputStream dataOutputStream = null; try { //建立服務端對象 serverSocket = new ServerSocket(8080); System.out.println("------服務端------"); System.out.println("已啓動,等待接收客戶端請求..."); while(true) { //接收到了一個客戶端對象 socket = serverSocket.accept(); inputStream = socket.getInputStream(); dataInputStream = new DataInputStream(inputStream); String request = dataInputStream.readUTF(); System.out.println("接收到了客戶端請求:"+request); //給客戶端做出響應 String response = "Hello World"; System.out.println("給客戶端做出的響應:"+response); outputStream = socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeUTF(response); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataOutputStream.close(); dataInputStream.close(); outputStream.close(); inputStream.close(); socket.close(); serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } ``` ```java import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class Client { public static void main(String[] args) { Socket socket = null; OutputStream outputStream = null; DataOutputStream dataOutputStream = null; InputStream inputStream = null; DataInputStream dataInputStream = null; try { socket = new Socket("127.0.0.1",8080); System.out.println("------客戶端------"); String request = "你好!"; System.out.println("客戶端說:"+request); outputStream = socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeUTF(request); //接收客戶端的響應 inputStream = socket.getInputStream(); dataInputStream = new DataInputStream(inputStream); String response = dataInputStream.readUTF(); System.out.println("服務端響應:"+response); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataInputStream.close(); inputStream.close(); dataOutputStream.close(); outputStream.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } ``` ### 基於UDP協議的網絡編程 UDP 全部的鏈接都是不可靠的,即不須要創建鏈接,直接發送數據。 UDP 的速度更快,可是可能會形成數據丟失,安全性不高,追求速度的應用能夠選擇 UDP。 TerminalA ```java import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketAddress; import java.net.SocketException; public class TerminalA { public static void main(String[] args) { try { //接收數據 byte[] buff = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(buff, buff.length); DatagramSocket datagramSocket = new DatagramSocket(8181); datagramSocket.receive(datagramPacket); String message = new String(datagramPacket.getData(),0,datagramPacket.getLength()); System.out.println("我是TerminalA,接收到了"+datagramPacket.getPort()+"傳來的數據:"+message); //發送數據 String reply = "我是TerminalA,已經接收到你發來的消息"; SocketAddress socketAddress = datagramPacket.getSocketAddress(); DatagramPacket datagramPacket2 = new DatagramPacket(reply.getBytes(),reply.getBytes().length,socketAddress); datagramSocket.send(datagramPacket2); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ``` TerminalB ```java import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class TerminalB { public static void main(String[] args) { try { //發送數據 String message = "我是TerminalB,你好!"; InetAddress inetAddress = InetAddress.getByName("localhost"); DatagramPacket datagramPacket = new DatagramPacket(message.getBytes(), message.getBytes().length,inetAddress,8181); DatagramSocket datagramSocket = new DatagramSocket(8080); datagramSocket.send(datagramPacket); //接收數據 byte[] buff = new byte[1024]; DatagramPacket datagramPacket2 = new DatagramPacket(buff, buff.length); datagramSocket.receive(datagramPacket2); String reply = new String(datagramPacket2.getData(),0,datagramPacket2.getLength()); System.out.println("我是TerminalB,接收到了"+datagramPacket2.getPort()+"返回的數據:"+reply); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ``` ### 多線程下的網絡編程 上述代碼都是基於單點鏈接的方式,即一個服務端對應一個客戶端,實際運行環境中一個服務端須要對應多個客戶端的,這種狀況能夠經過多線程來模擬。 ServerRunnable ```java import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; public class ServerRunnable implements Runnable { private Socket socket; public ServerRunnable(Socket socket) { // TODO Auto-generated constructor stub this.socket = socket; } @Override public void run() { // TODO Auto-generated method stub InputStream inputStream = null; DataInputStream dataInputStream = null; try { inputStream = this.socket.getInputStream(); dataInputStream = new DataInputStream(inputStream); String message = dataInputStream.readUTF(); System.out.println(message); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataInputStream.close(); inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } ``` ServerThread ```java import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerThread { public static void main(String[] args) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(8080); System.out.println("服務器已啓動......"); while(true) { Socket socket = serverSocket.accept(); ServerRunnable serverRunnable = new ServerRunnable(socket); Thread thred = new Thread(serverRunnable); thred.start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ``` ClientRunnable ```java import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class ClientRunnable implements Runnable { private int num; public ClientRunnable(int num) { // TODO Auto-generated constructor stub this.num = num; } @Override public void run() { // TODO Auto-generated method stub Socket socket = null; OutputStream outputStream = null; DataOutputStream dataOutputStream = null; try { socket = new Socket("localhost", 8080); String mess = "我是客戶端"+this.num; outputStream = socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeUTF(mess); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataOutputStream.close(); outputStream.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } ``` ClientThread ```java public class ClientThread { public static void main(String[] args) { for(int i = 0;i<100;i++) { ClientRunnable clientRunnable = new ClientRunnable(i); Thread thread = new Thread(clientRunnable); thread.start(); } } } ``` MyServerThread ```java import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; public class MyServerThread extends Thread { private Socket socket; public MyServerThread(Socket socket) { // TODO Auto-generated constructor stub this.socket = socket; } @Override public void run() { // TODO Auto-generated method stub InputStream inputStream = null; DataInputStream dataInputStream = null; try { inputStream = this.socket.getInputStream(); dataInputStream = new DataInputStream(inputStream); String message = dataInputStream.readUTF(); System.out.println(message); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataInputStream.close(); inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } ``` ServerThread2 ```java import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerThread2 { public static void main(String[] args) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(9090); System.out.println("------服務器啓動------"); while(true) { Socket socket = serverSocket.accept(); MyServerThread myServerThread = new MyServerThread(socket); myServerThread.start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ``` MyClientThread ```java import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class MyClientThread extends Thread { private int num; public MyClientThread(int num) { // TODO Auto-generated constructor stub this.num = num; } @Override public void run() { // TODO Auto-generated method stub Socket socket = null; OutputStream outputStream = null; DataOutputStream dataOutputStream = null; try { socket = new Socket("localhost", 9090); String mess = "我是客戶端"+this.num; outputStream = socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeUTF(mess); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataOutputStream.close(); outputStream.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } ``` ClientThread2 ```java public class ClientThread2 { public static void main(String[] args) { for(int i=0;i<100;i++) { MyClientThread myClientThread = new MyClientThread(i); myClientThread.start(); } } } ```
Client.javajava
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class Client { public static void main(String[] args) { Socket socket = null; OutputStream outputStream = null; DataOutputStream dataOutputStream = null; InputStream inputStream = null; DataInputStream dataInputStream = null; try { socket = new Socket("127.0.0.1",8080); System.out.println("------客戶端------"); String request = "你好!"; System.out.println("客戶端說:"+request); outputStream = socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeUTF(request); //接收客戶端的響應 inputStream = socket.getInputStream(); dataInputStream = new DataInputStream(inputStream); String response = dataInputStream.readUTF(); System.out.println("服務端響應:"+response); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataInputStream.close(); inputStream.close(); dataOutputStream.close(); outputStream.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
ClientRunnable.java編程
import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class ClientRunnable implements Runnable { private int num; public ClientRunnable(int num) { // TODO Auto-generated constructor stub this.num = num; } @Override public void run() { // TODO Auto-generated method stub Socket socket = null; OutputStream outputStream = null; DataOutputStream dataOutputStream = null; try { socket = new Socket("localhost", 8080); String mess = "我是客戶端"+this.num; outputStream = socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeUTF(mess); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataOutputStream.close(); outputStream.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
ClientThread.java安全
public class ClientThread { public static void main(String[] args) { for(int i = 0;i<100;i++) { ClientRunnable clientRunnable = new ClientRunnable(i); Thread thread = new Thread(clientRunnable); thread.start(); } } }
ClentThread2.java服務器
public class ClientThread2 { public static void main(String[] args) { for(int i=0;i<100;i++) { MyClientThread myClientThread = new MyClientThread(i); myClientThread.start(); } } }
MyClentThread.java網絡
import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class MyClientThread extends Thread { private int num; public MyClientThread(int num) { // TODO Auto-generated constructor stub this.num = num; } @Override public void run() { // TODO Auto-generated method stub Socket socket = null; OutputStream outputStream = null; DataOutputStream dataOutputStream = null; try { socket = new Socket("localhost", 9090); String mess = "我是客戶端"+this.num; outputStream = socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeUTF(mess); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataOutputStream.close(); outputStream.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
MyServerThread.java多線程
import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; public class MyServerThread extends Thread { private Socket socket; public MyServerThread(Socket socket) { // TODO Auto-generated constructor stub this.socket = socket; } @Override public void run() { // TODO Auto-generated method stub InputStream inputStream = null; DataInputStream dataInputStream = null; try { inputStream = this.socket.getInputStream(); dataInputStream = new DataInputStream(inputStream); String message = dataInputStream.readUTF(); System.out.println(message); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataInputStream.close(); inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Server.javasocket
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; OutputStream outputStream = null; InputStream inputStream = null; DataInputStream dataInputStream = null; DataOutputStream dataOutputStream = null; try { //建立服務端對象 serverSocket = new ServerSocket(8080); System.out.println("------服務端------"); System.out.println("已啓動,等待接收客戶端請求..."); while(true) { //接收到了一個客戶端對象 socket = serverSocket.accept(); inputStream = socket.getInputStream(); dataInputStream = new DataInputStream(inputStream); String request = dataInputStream.readUTF(); System.out.println("接收到了客戶端請求:"+request); //給客戶端做出響應 String response = "Hello World"; System.out.println("給客戶端做出的響應:"+response); outputStream = socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeUTF(response); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataOutputStream.close(); dataInputStream.close(); outputStream.close(); inputStream.close(); socket.close(); serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
ServerRunnable.javaide
import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; public class ServerRunnable implements Runnable { private Socket socket; public ServerRunnable(Socket socket) { // TODO Auto-generated constructor stub this.socket = socket; } @Override public void run() { // TODO Auto-generated method stub InputStream inputStream = null; DataInputStream dataInputStream = null; try { inputStream = this.socket.getInputStream(); dataInputStream = new DataInputStream(inputStream); String message = dataInputStream.readUTF(); System.out.println(message); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataInputStream.close(); inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
ServerThread.javathis
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerThread { public static void main(String[] args) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(8080); System.out.println("服務器已啓動......"); while(true) { Socket socket = serverSocket.accept(); ServerRunnable serverRunnable = new ServerRunnable(socket); Thread thred = new Thread(serverRunnable); thred.start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
ServerThread2.javaspa
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerThread2 { public static void main(String[] args) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(9090); System.out.println("------服務器啓動------"); while(true) { Socket socket = serverSocket.accept(); MyServerThread myServerThread = new MyServerThread(socket); myServerThread.start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
TerminalA.java
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketAddress; import java.net.SocketException; public class TerminalA { public static void main(String[] args) { try { //接收數據 byte[] buff = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(buff, buff.length); //TerminaA的端口8181 DatagramSocket datagramSocket = new DatagramSocket(8181); datagramSocket.receive(datagramPacket); String message = new String(datagramPacket.getData(),0,datagramPacket.getLength()); System.out.println("我是TerminalA,接收到了"+datagramPacket.getPort()+"傳來的數據:"+message); //發送數據 String reply = "我是TerminalA,已經接收到你發來的消息"; SocketAddress socketAddress = datagramPacket.getSocketAddress(); DatagramPacket datagramPacket2 = new DatagramPacket(reply.getBytes(),reply.getBytes().length,socketAddress); datagramSocket.send(datagramPacket2); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
TerminalB.java
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class TerminalB { public static void main(String[] args) { try { //發送數據 String message = "我是TerminalB,你好!"; InetAddress inetAddress = InetAddress.getByName("localhost"); DatagramPacket datagramPacket = new DatagramPacket(message.getBytes(), message.getBytes().length,inetAddress,8181); //TerminalB的端口8080 DatagramSocket datagramSocket = new DatagramSocket(8080); datagramSocket.send(datagramPacket); //接收數據 byte[] buff = new byte[1024]; DatagramPacket datagramPacket2 = new DatagramPacket(buff, buff.length); datagramSocket.receive(datagramPacket2); String reply = new String(datagramPacket2.getData(),0,datagramPacket2.getLength()); System.out.println("我是TerminalB,接收到了"+datagramPacket2.getPort()+"返回的數據:"+reply); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }