TCP在雙方傳輸數據前,發送方先請求建立連接,接收方同意建立連接後才能傳輸數據。(打電話:先撥號,等對方同意接聽後,才能交流)。。。高可靠性
UDP不需要建立連接(發短信)。不可靠,可能出現數據丟失等,但效率高,實時性高。
————————————————————————————————————————————————————————————————————————————
服務器端:
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSocketTest {
public static void main(String[] args) throws IOException {
// 新建一個服務器端的套接字 Server端監聽10000端口
ServerSocket serverSocket = new ServerSocket(10000);
// 建立連接,此時進入阻塞狀態
Socket socket = serverSocket.accept();
System.out.println("Connected: " + socket.getRemoteSocketAddress());
// socket從客戶端讀取數據
InputStream inputStream = socket.getInputStream();
byte[] b = new byte[1024];
int length = inputStream.read(b);
System.out.println(length + " Bytes Received");
}
}
客戶端代碼:
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class ClientSocketTest {
public static void main(String[] args) throws IOException {
//新建一個客戶端的套接字
Socket socket = new Socket("127.0.0.1", 10000);
// 用socket往服務器端發送數據
OutputStream outputStream = socket.getOutputStream();
byte[] b = new byte[2];
outputStream.write(b);
}
}
運行結果:
Connected: /127.0.0.1:60361
2 Bytes Received