Socket的实例一

import java.io.*澳门新葡亰游戏网址,;
import java.net.Socket;
import java.net.SocketException;

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

public class TestClient {
    public static void main(String args[]) {
        try {        
            Socket s1 = new
Socket(“localhost”,8884);
            InputStream is = s1.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            OutputStream os = s1.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new
BufferedReader(isr);
            
            String info;
            while(true){
                info = br.readLine();
                dos.writeUTF(info);
                if(info.equals(“bye”))
                    break;
                info = dis.readUTF();
                System.out.println(“对方说: ” + info);
                if(info.equals(“bye”))
                    break;
            }
            dis.close();            
            dos.close();
            s1.close();
        }catch (SocketException e)
{
                System.out.println(“网络连接异常,程序退出!”);
        }catch (IOException e) {
            e.printStackTrace();        
        }
    }
}

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();        
        }
    }
}

 

网站地图xml地图