灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:2654回复:0

java例程练习(网络编程[简单网络连接试验])

楼主#
更多 发布于:2012-09-08 09:44

import java.net.*;
import java.io.*;

public class TestTCPServer {
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(6666);//阻塞式的
            
            while(true) {
                
                //未经行异常处理!
//          Socket s = ss.accept();
//          DataInputStream dis =  
//              new DataInputStream(s.getInputStream());
//          System.out.println(dis.readUTF());//也是阻塞式的
//          dis.close();
//          s.close();
                
                Socket s1 = ss.accept();
                OutputStream os = s1.getOutputStream();
                DataOutputStream DOS = new DataOutputStream(os);
                DOS.writeUTF("Hello," + s1.getInetAddress() +  
                            "port#" + s1.getPort()+ " bye-bye!");
                
                DOS.close();
                s1.close();
                
                
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("程序运行出错:  " + e);
        }
        
        
        
    }
}
[java]
import java.net.*;
import java.io.*;
public class TestTCPClient {
    public static void main(String[] args) {
        try {
            Socket s = new Socket("127.0.0.1", 6666);
            //未经行异常处理!
//          OutputStream os = s.getOutputStream();
//          DataOutputStream DOS = new DataOutputStream(os);
//          
//          Thread.sleep(3000);
//          DOS.writeUTF("Hello Server!");
//          DOS.flush();
//          DOS.close();
//          s.close();
            
            InputStream is = s.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            System.out.println(dis.readUTF());
            dis.close();
            s.close();
            
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
}


摘自 Yours风之恋


喜欢0 评分0
游客

返回顶部