多线程部分:
/** * Created by LiuHuiChao on 2016/3/11. * 服务器端线程处理类 */ 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{ //3,获取输入流,用来读取客户端所发送的登录信息 is=socket.getInputStream(); isr=new InputStreamReader(is); br=new BufferedReader(isr);//为输入流添加缓冲 String info=null; while ((info=br.readLine())!=null){//读取数据不为空,循环读取 System.out.println("我是服务器,客户端说:"+info); } //4,获取输出流,用来响应客户端的请求 os=socket.getOutputStream(); pw=new PrintWriter(os);//包装为打印流 pw.write("欢迎哟,思密达~~·"); pw.flush();//将缓冲输出 socket.shutdownOutput();//关闭输出流 }catch (Exception e){ }finally { //5,关闭相关的资源 try { pw.close(); os.close(); br.close(); isr.close(); is.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
服务端代码:
/** * Created by LiuHuiChao on 2016/3/9. * 基于TCP协议的socket通信,实现用户登录 * 服务器端 */ public class ServerSocketClass { public static void main(String[] args)throws Exception { //1,创建一个服务器端socket,即serverSocket,指定绑定的端口,并监听此端口 ServerSocket serverSocket=new ServerSocket(8888); Socket socket=null; //2,调用accept方法等待客户端的连接 System.out.println("----服务器即将启动----前方高能---"); int ClientCount=0; while (true){ //调用accept方法,等待客户端的连接 socket=serverSocket.accept(); //创建一个新的线程 ServerThread st=new ServerThread(socket); //启动线程 st.start();//启动新线程 ClientCount++; System.out.println("客户端的数量:"+ClientCount); InetAddress address=socket.getInetAddress(); System.out.println("当前客户端的IP:"+address.getHostAddress()); } //serverSocket.close(); } }
客户端代码:
/** * Created by LiuHuiChao on 2016/3/9. * 客户端 */ public class ClientServerClass { public static void main(String[] args)throws Exception { //1,创建一个Socket,指定服务器地址和端口 Socket socket=new Socket("localhost",8888); //2,获取输出流,用来向服务器端发送信息 OutputStream os=socket.getOutputStream(); PrintWriter pw=new PrintWriter(os);//将输出流包装成打印流 pw.write("用户名:admin;密码:123"); pw.flush(); socket.shutdownOutput();//关闭输出流 //3,获取输入流,并读取服务器端的响应信息 InputStream is=socket.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String info=null; while ((info=br.readLine())!=null){//读取数据不为空,循环读取 System.out.println("我是客户端,服务器端说:"+info); } //4,关闭其他相关资源 br.close(); is.close(); pw.close(); os.close(); socket.close(); } }