goback add

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

3152 点击·0 回帖
灯火互联
楼主

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