java Socket通信简单实例

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

public class ClientTest {
    public static void main(String[] args) throws Exception {
        Socket s = new Socket("localhost", 8888);
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        dos.writeUTF("client:hello");
        DataInputStream dis = new DataInputStream(s.getInputStream());
        System.out.println(dis.readUTF());
        
        //s.close();
    }
}
import java.io.*;
import java.net.*;
import java.net.ServerSocket;

public class ServerTest {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(8888);
        Socket s = ss.accept();
        
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        dos.writeUTF("server: hi, I am server !");
        DataInputStream dis = new DataInputStream(s.getInputStream());
        
        System.out.println(dis.readUTF());
        //s.close();
    }
}

 

你可能感兴趣的:(java socket)