Chinaunix首页 | 论坛 | 博客
  • 博客访问: 442775
  • 博文数量: 78
  • 博客积分: 2307
  • 博客等级: 上尉
  • 技术积分: 920
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-04 00:31
个人简介

IT老鸟,信息安全硕士。

文章分类
文章存档

2017年(2)

2012年(21)

2011年(55)

分类: Java

2011-07-18 17:36:06

  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.Scanner;
  4. public class ClientTest {
  5.  public static void main(String args[]) throws IOException
  6.         {
  7.         InetAddress addr=InetAddress.getByName(null);
  8.         System.out.println("addr="+addr);
  9.         Socket socket=new Socket(addr,ServerTest.PORT);
  10.         Scanner sc1 = new Scanner(System.in);
  11.          String js=sc1.nextLine();
  12.          System.out.println(js); //打印输入内容
  13.         try{
  14.             System.out.println("socket="+socket); //发送的情况
  15.             BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream() ) );//这行不太懂
  16.             PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream() ) ),true );
  17.   
  18.                 out.println(js);//走
  19.   
  20.             out.println("END");
  21.             }finally{
  22.                 System.out.println("closing...");
  23.                 socket.close();
  24.             }
  25.         }
  26. }
  1. import java.io.*;
  2. import java.net.*;
  3. public class ServerTest {
  4.        
  5.         public static final int PORT =8080;
  6.         public static void main(String args[]) throws IOException{
  7.             ServerSocket s=new ServerSocket(PORT);
  8.             System.out.println("started:"+s);
  9.             try{
  10.                 Socket socket=s.accept(); //监听数据
  11.                 try{
  12.                     System.out.println("Connection accepted:"+socket);
  13.                     BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream() ) );
  14.                     PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()) ),true);
  15.                     while(true)
  16.                         {
  17.                         String str=in.readLine();//来.
  18.                         if(str.equals("END") )break; //收到END就结束监听
  19.                         System.out.println("Echoing:"+str);
  20.                         out.println(str);//回
  21.                         }
  22.                     }finally{
  23.                         System.out.println("closing");
  24.                         socket.close();
  25.                     }
  26.                    
  27.                    
  28.             }finally{
  29.                 s.close();
  30.             }
  31.         }
  32.            
  33.     }
  34. 分别运行客户端和服务端.输入hello world 搞定.
阅读(1737) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~