多线程TCP的socket通信
应用多线程来实现服务器与多客户端之间的通信。
基本步骤:
1.服务器端创建ServerSocket,循环调用accept()等待客户端的连接
2.客户端创建一个socket并请求和服务器端的连接
3.服务器端接收客户端的请求,创建socket与该客户端建立专线连接
4.建立连接的两个socket在一个单独的线程上对话
5.服务器端继续等待新的客户端的连接
Server.java
public class Server {
public static void main(String[] args) throws IOException{
//1、创建一个服务器端的socket,指定绑定的端口,并侦听此端口
ServerSocket server = new ServerSocket(8888);
System.out.println("********服务端即将启动,等待客户端的连接********");
int count = 0;
//2、开始侦听,等待客户端的连接
while(true){
Socket socket = server.accept();
ServerThread thread = new ServerThread(socket);
thread.start();
count++;
System.out.println("客户端的数量:"+count);
InetAddress address = socket.getInetAddress();
System.out.println("客户端的ip:"+address.getHostAddress());
}
}
}
ServerThread.java
public class ServerThread extends Thread {
//和本线程相关的socket
Socket socket = null;
public ServerThread(Socket socket){
this.socket = socket;
}
//线程执行操作,响应客户端的请求
public void run(){
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
OutputStream os = null;
PrintWriter pw = null;
try {
//3、获取输入流,用来读取客户端发送的信息
is = socket.getInputStream();//字节输入流
isr = new InputStreamReader(is);//字符输入流
br = new BufferedReader(isr);//缓冲输入流
String info = null;
while((info=br.readLine()) != null){
//循环读取数据
System.out.println("客户端说:"+info);
}
socket.shutdownInput();//关闭输入流
os = socket.getOutputStream();//字节输出流
pw = new PrintWriter(os);//打印输出流
pw.write("服务器端已接受你的请求,允许登录");
pw.flush();
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
//4、关闭资源
if(pw != null)
pw.close();
if(os != null)
os.close();
if(br != null)
br.close();
if(isr != null)
isr.close();
if(is != null)
is.close();
if(socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Client.java
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException{
//1、创建客户端socket,指定服务器地址和端口
Socket socket = new Socket("127.0.0.1",8888);
System.out.println("******客户端已准备就绪*******");
//2、给服务端发送数据
OutputStream os = socket.getOutputStream();//字节流
PrintWriter pw = new PrintWriter(os);//打印流
pw.write("用户名:admin;密码:123456");
pw.flush();
socket.shutdownOutput();//关闭输出流
InputStream is = socket.getInputStream();//字节输入流
InputStreamReader isr = new InputStreamReader(is);//字符输入流
BufferedReader br = new BufferedReader(isr);//缓冲输入流
String info = null;
while((info=br.readLine()) != null){
System.out.println("服务端说:"+info);
}
socket.shutdownInput();//关闭输入流
//3、关闭资源
br.close();
isr.close();
is.close();
pw.close();
os.close();
socket.close();
}
}