public class Server {
public static void main(String[] args) throws IOException {
//1:建立服务器+指定端口 ServerSocket(int Port);
ServerSocket server=new ServerSocket(8888);
//2:接收客户端连接 阻塞式
Socket socket=server.accept();
System.out.println("一个客户端建立连接");
//3:发送数据
String msg="欢迎使用";
//输出流:
BufferedWriter bw=new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream()
)
);
bw.write(msg);
bw.flush();
}
}
public class Client {
/**
* @param args
* @throws UnknownHostException
* @throws IOException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
//1:创建客户端 必须指定服务器地址+服务器指定端口(客户端的端口自动分配)
//Socket(String host,int port)
Socket client=new Socket("localhost",8888);
//2:接收数据
BufferedReader br=new BufferedReader(
new InputStreamReader(
client.getInputStream()
)
);
br.readLine();
}
} |
|