一个基于Socket Coding的小型聊天应用
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 3000);
BufferedReader inputStream = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter outputStream = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String clientMsg;
String serverMsg;
Scanner sc = new Scanner(System.in);
clientMsg = sc.nextLine();
while (clientMsg != "bye") {
outputStream.write(clientMsg + "\r\n");
outputStream.flush();
serverMsg = inputStream.readLine();
System.out.println("serever say:" + serverMsg);
clientMsg = sc.nextLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Server {
public static final int port = 3000;
public static void main(String[] args) {
try {
ServerSocket ss= new ServerSocket(port);
System.out.println("开始在3000上启动服务器");
Socket socket = ss.accept();
System.out.println("建立了连接");
BufferedReader inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter outputStream = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String clientMsg;
String serverMsg;
Scanner sc = new Scanner(System.in);
clientMsg = inputStream.readLine();
while (clientMsg != "bye") {
System.out.println(clientMsg);
serverMsg = sc.nextLine();
outputStream.write(serverMsg + "\r\n");
outputStream.flush();
clientMsg = inputStream.readLine();
}
}catch (IOException e) {
e.printStackTrace();
}
}
}
这里有一个注意点,就是Server和Client的Port必须保持一致。并且,有时候设定的端口号不起作用,因为电脑上运行的其他程序可能已经把这个端口号占用了,这时候就需要换一个端口号。