Java Socket应用(三)多线程实现多客户端的通信

服务器线程处理类ServerThread.java :

package com.yijia;

import java.io.*;
import java.net.Socket;

/**
 * 创建时间:2018/10/4 14:59
 * 作者:
 * 邮箱:[email protected]
 * 

* 服务器线程处理类 */ public class ServerThread extends Thread { //和本线程相关的Socket Socket socket = null; //构造方法 public ServerThread(Socket socket) { this.socket = socket; } //线程执行的操作,响应客户端的请求 @Override public void run() { InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; OutputStream os = null; PrintWriter pw = null; try { //获取输入流,读取客户端信息 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();//调用flush()方法将缓冲输出 } catch (IOException e) { e.printStackTrace(); } finally { //关闭资源 try { 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(); } } } }

 修改服务器端代码Service.java:

package com.yijia;

import java.beans.IndexedPropertyChangeEvent;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 创建时间:2018/10/4 12:25
 * 作者:
 * 邮箱:[email protected]
 * 

* 基于TCP协议的Socket通信,实现用户登录 * 服务器端 */ public class Service { public static void main(String[] args) { try { //创建一个服务器端Socket,即ServiceSocket,指定绑定的端口,并监听此端口 ServerSocket serviceSocket = new ServerSocket(8888); Socket socket = null; //记录客户端的数量 int count = 0; System.out.println("***服务器即将启动,等待客户端的连接***"); //循环监听等待客户端的连接 while (true) { //调用accept()方法开始监听,等待客户端的连接 socket = serviceSocket.accept(); //创建一个新的线程 ServerThread serverThread = new ServerThread(socket); //启动线程 serverThread.start(); count++;//统计客户端的数量 System.out.println("客户端的数量:" + count); InetAddress address = socket.getInetAddress(); System.out.println("当前客户端的IP:"+address.getHostAddress()); } } catch (IOException e) { e.printStackTrace(); } } }

 

你可能感兴趣的:(Java,Java,Socket)