Socket的实例一

作者在 2010-05-24 09:40:07 发布以下内容


import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;

public class TestServer {
    public static void main(String args[]) {
        try {        
            ServerSocket s = new ServerSocket(8888);
            while (true) {
                Socket s1 = s.accept();
                OutputStream os = s1.getOutputStream();
                DataOutputStream dos = new DataOutputStream(os);
                dos.writeUTF("你好,客户端地址信息: " + s1.getInetAddress()
                    + "\t客户端通信端口号: " + s1.getPort());
                dos.writeUTF("再见!");
                dos.close();
                s1.close();
            }
        }catch (IOException e) {
            e.printStackTrace();        
        }
    }
}
 


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

public class TestClient {
    public static void main(String args[]) {
        try {
            Socket s1 = new Socket("127.0.0.1", 8888);
            InputStream is = s1.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            System.out.println(dis.readUTF());
            System.out.println(dis.readUTF());
            dis.close();
            s1.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}
网络编程 | 阅读 1105 次
文章评论,共0条
游客请输入验证码
浏览290899次