java中的socket编程案例,一个是服务端,一个是客户端,运行时先启动服务端,再启动客户端。
//客户端 package com.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; 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.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 (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } } } //服务端 package com.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; 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(8888); //2.调用accept()方法开始监听,等待客服端的连接 System.out.println("***服务器即将启动,等待客户端的连接***"); Socket socket=serverSocket.accept(); //3.获取输入流,并获取客户端信息 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();//关闭输入流 //4.获取输出流,响应客户端请求 OutputStream os=socket.getOutputStream();//字节输出流 PrintWriter pw=new PrintWriter(os);//将输出流包装为打印流 pw.write("欢迎你"); pw.flush(); //5.关闭资源 pw.close(); os.close(); br.close(); isr.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }