1.
socket 通信原理:
基於TCP的socket通信。
2.多線程的優先級。
while(true){
socket = serverSocket.accept();
//創建一個新線程
ServerThread serverThread=new ServerThread(socket);
//未設置優先級,可能導致運行時速度非常慢,可降低優先級。
serverThread.setPriority(4);//設置線程的優先級,範圍(1,10);默認爲5
serverThread.start();//啓動線程.
count++;//統計客戶端數量
System.out.println("客戶端數量:"+count);
InetAddress address=socket.getInetAddress();
System.out.println("當前客戶端IP:"+address.getHostAddress());
}
3.是否關閉輸出輸入流
對於同一個socket,如果關閉了輸出流。則與該輸出流關聯的socket也會被關閉,所以一般不用關閉流,直接關閉socket。
4.使用TCP傳輸對象。
//創建客戶端Socket,指定服務器地址和端口號
Socket sk=new Socket("localhost", 8888);
//獲取輸出流,向服務器發送信息
OutputStream os=sk.getOutputStream();//字節輸出流
//使用對象序列化流
ObjectOutputStream oos=new ObjectOutputStream(os);
User user=new User("admin",123);
oos.writeObject(user);//序列化
sk.shutdownOutput();//關閉輸出流