标签:
一个服务端与多个客户端交互的例子
package j2se.socket; import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; /** * Created by jingqing.zhou on 2015/6/17. * 基于tcp协议的socket通信,实现用户登录 * 服务器端 */ public class server { public static void main(String[] args) { //1.创建一个服务器端socket try { ServerSocket sst = new ServerSocket(8999); System.out.println("服务器即将启动,等待客户端的链接=====>"); //记录客户端的数量 int count = 0 ; while (true){ Socket socket = sst.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(); } } }
package j2se.socket; import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * Created by jingqing.zhou on 2015/6/17. * 基于tcp协议的socket通信,实现用户登录 * 服务器端线程处理类 */ public class ServerThread extends Thread{ //和本线程相关的socket Socket socket = null ; public ServerThread(Socket socket){ this.socket = socket; } //线程的执行操作,响应客户端的请求 public void run(){ //获取输入流,并读取客户端信息 InputStream is =null; InputStreamReader isr=null ; BufferedReader bufferedReader =null ; OutputStream os=null ; PrintWriter pw=null ; try { is = socket.getInputStream();//字节输入流 isr = new InputStreamReader(is);//将字节流包装为字符流 bufferedReader = new BufferedReader(isr);//为输入流添加缓冲 String info = null; //循环读取客户端信息 while ((info = bufferedReader.readLine()) != null) { System.out.println("我是服务器,客户端说:" + info); } socket.shutdownInput();//关闭输入流 //获取输出流,用于响应客户端请求 os = socket.getOutputStream(); pw = new PrintWriter(os);//将输出流包装为打印流 pw.write("欢迎您:admin!!"); pw.flush(); }catch (IOException e){ e.printStackTrace(); }finally { //关闭资源 try{ bufferedReader.close(); pw.close(); os.close(); isr.close(); is.close(); socket.close(); }catch (IOException e){ e.printStackTrace(); } } } }
package j2se.socket; import java.io.*; import java.net.Socket; /** * Created by jingqing.zhou on 2015/6/17. */ public class client { public static void main(String[] args) { try { //创建客户端socket,指定服务器地址和端口 Socket socket = new Socket("localhost",8999); //获取输出流,用来向服务器端发送信息 OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os);//将输出流包装为打印流 pw.write("用户名:admin1111;密码:123"); 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.printf("我是客户端,服务器端说:"+ info); } socket.shutdownInput();//关闭输入流 br.close(); is.close(); pw.close(); os.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
标签:
原文地址:http://my.oschina.net/reesechou/blog/467857