Java的Socket通信----通过 Socket 实现 TCP 编程之多线程demo(2)
JAVA Socket简介
所谓socket 通常也称作”套接字“,用于描述IP地址和端口,是一个通信链的句柄。应用程序通常通过”套接字”向网络发出请求或者应答网络请求。
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; public class Client { public static void main(String[] args) { try { Socket socket = new Socket("localhost", 8080);//1.创建客户端Socket,指定服务器地址和端口 //2.获取输出流,向服务器端发送信息 OutputStream os = socket.getOutputStream();//字节输出流 PrintWriter pw = new PrintWriter(os);//将输出流包装为打印流 pw.write("用户名:whf;密码:789"); 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(); } catch (Exception e) { // TODO: handle exception } } }
import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try { //1.创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听此端口 ServerSocket serverSocket = new ServerSocket(8080); Socket socket = null; int count = 0;//记录客户端的数量 System.out.println("***服务器即将启动,等待客户端的连接***"); while (true) { socket = serverSocket.accept();//调用accept()方法开始监听,等待客户端的连接 //创建一个新的线程 ServerThread serverThread = new ServerThread(socket); serverThread.start();//启动线程 count++; System.out.println("客户端的数量:" + count); InetAddress address = socket.getInetAddress(); System.out.println("当前客户端的IP:" + address.getHostAddress()); } } catch (Exception e) { e.printStackTrace(); } } }
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; /** * * @ClassName: ServerThread * @Description: 服务器线程处理类 * @author: xfzhong * @date: */ public class ServerThread extends Thread{ Socket socket=null;// 和本线程相关的Socket 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();//调用flush()方法将缓冲输出 } catch (Exception 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 (Exception e2) { e2.printStackTrace(); } } } }