package com.iport.base.enterprise.web.view; import org.apache.log4j.net.SocketServer; import org.apache.log4j.net.SocketServer; import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; /** * 基于TCP协议的Socket通信,实现用户登录 */ public class Server { public static void main(String[] args) { try { //创建一个服务器端socket,即ServerSocket,指定绑定的端口,并监听此端口客户端 ServerSocket socketServer = new ServerSocket(8888); Socket socket = null; int count = 0; System.out.println("****服务器即将启动,等待用户接入****"); while (true){ socket = socketServer.accept(); ServerThread serverThread = new ServerThread(socket); serverThread.start(); count++; System.out.println("客户端数量:"+count); InetAddress address = socket.getInetAddress(); System.out.println("客户duan:"+address.getHostAddress()); } } catch (IOException e) { e.printStackTrace(); } } }
package com.iport.base.enterprise.web.view; import java.io.*; import java.net.Socket; /** * 客户端 */ public class Client { public static void main(String[] args) { try { //1.创建客户端Socket,指定服务器地址和端口 Socket socket = new Socket("localhost",8888); //2.获取输出流,向服务器端发送信息 OutputStream os = socket.getOutputStream();//字节输出流 PrintWriter pw = new PrintWriter(os);//将输出流包装为打印流 // pw.write("用户名:admin;密码:123"); pw.write("用户名:tom;密码:456"); pw.flush(); socket.shutdownOutput();//关闭输出流 //接收 InputStream is = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String info = null; while ((info=br.readLine())!=null){ System.out.println("我是客户端:"+info); } //关闭资源 br.close(); is.close(); pw.close(); os.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
多线程:
package com.iport.base.enterprise.web.view; import java.io.*; import java.net.Socket; /** * 服务器线程处理类 */ public class ServerThread extends Thread { // 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 { //获取输入流,并读取客户端信息 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(); } catch (IOException e) { e.printStackTrace(); }finally { //关闭资源 try { if (pw != null) { pw.close(); } if (os != null) { os.close(); } if (br != null) { br.close(); } if (is != null) { is.close(); } if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }