Multi-threaded applications to enable communication between the server and multi-client
1. Based on Socket TCP protocol implementation
Tools
public class ThreadUtils extends Thread{
private Socket socket = null;
public ThreadUtils (Socket socket){//创建构造方法
this.socket = socket;
}
public void run() {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader bf = null;
try {
is = socket.getInputStream(); //获得字节输入流
isr = new InputStreamReader(is);//将字节输入流转为 字符输入流
bf = new BufferedReader(isr); //将字符输入流加入缓冲区
String data = null;//返回的数据
while (bf.readLine()!=null){
data = bf.readLine(); //读取数据
}
socket.shutdownInput();//关闭输入流
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(bf!=null)
bf.close();
if(isr!=null)
isr.close();
if(is!=null)
is.close();
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Class Action
2. Based on Socket UDP protocol implementation
UDP protocol (User Datagram Protocol) is a connectionless and unreliable, disordered.
Speed is relatively fast, the time for transmission, the transmitted data will first be defined data packets (Datagram) , the data specified in the data packets to be achieved Socket (host address and port number), and then transmits the data packets out.
Related operations categories:
1. of DatagramPacket : represents a datagram packet
2. DatagramSocket : end communication for the class
Specific implementation
If you want to respond to the client, you can call DatagramPacket.getInetAddress (); this method to get the client Inetaddress instance
back in to send a datagram
An object can be transmitted using an ObjectOutputStream