服务器端代码:
package socket;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static int port = 8088;
public static String ip = "";
public static void main(String[] args) throws IOException {
//①启动服务器
ServerSocket server = new ServerSocket(port);
System.out.println("server running...");
//②监听Socket
Socket socket = server.accept();
//③IO流
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
String client = null;
//如果接收到客户端的exit信号则关闭Socket
while(!"exit".equalsIgnoreCase(client = br.readLine())){
System.out.println("from client say:"+client);
pw.println("server get your info :" +client);
pw.flush();
}
br.close();
pw.close();
socket.close();
server.close();
}
}
客户端代码:
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
//连接服务器
Socket socket = new Socket(Server.ip,Server.port);
System.out.println("client running...");
System.out.println("-----insert your info:");
//用户在控制台输入向服务器发送的信息
BufferedReader brConsole = new BufferedReader(new InputStreamReader(System.in));
//IO流
PrintWriter pw = new PrintWriter(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String server = null;
//如果用户输入exit则关闭Socket
while(!"exit".equalsIgnoreCase(server = brConsole.readLine())){
pw.println(server);
pw.flush();
System.out.println("from server say:"+br.readLine());
}
//当用户输入exit时,把exit信息发送给服务器,服务器关闭当前Socket
pw.println(server);
pw.flush();
pw.close();
brConsole.close();
br.close();
socket.close();
}
}