聊天室的服务端
public class Server {
private ServerSocket serverSocket;
public Server(){
try {
System.out.println("正在启动服务端...");
serverSocket = new ServerSocket(8088);
System.out.println("服务端启动完毕!");
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() throws IOException {
try {
System.out.println("等待客户端连接.......");
/**
* 阻塞方法
*/
Socket socket =serverSocket.accept();
System.out.println("一个客户端连接了");
/**
* 通过刚接受连接的socket,获取输入流来读取该客户端发送过来的信息
*/
InputStream in = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
System.out.println("客户端说:"+line);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Server server = new Server();
server.start();
}
}
聊天室的客户端
public class Client {
/**
* 套接字
*/
private Socket socket;
public Client(){
/**
* socket实例化需要传入两个参数
* 参数1:服务端的地址信息
* 参数2:服务端打开的服务端口
* 客户端通过服务端的地址找到网络上的服务器计算机,通过端口可以连接上该机器上运行的服务端应用程序
*/
try{
System.out.println("正在连接服务器");
socket =new Socket("localhost",8088);
System.out.println("与服务端建立连接");
}catch(IOException e){
e.printStackTrace();
}
}
public void start() {
/**
* 客户端向服务端发送数据,则需要使用的socket获取输出流
*/
try {
OutputStream out =socket.getOutputStream();
OutputStreamWriter osw =new OutputStreamWriter(out, StandardCharsets.UTF_8);
BufferedWriter bw =new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw,true);
Scanner scanner = new Scanner(System.in);
while (true) {
String line = scanner.nextLine();
if ("exit".equals(line)) {
break;
}
pw.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client();
client.start();
}
}