当前位置: 代码迷 >> Web前端 >> 利用Socket跟ServerSocket模拟用户-服务器通讯
  详细解决方案

利用Socket跟ServerSocket模拟用户-服务器通讯

热度:475   发布时间:2013-12-29 13:07:03.0
利用Socket和ServerSocket模拟用户-服务器通讯

客户端:

?????? public class ClientSocketTest {

?public static void main(String[] args) {
??try {
???//本地计算机模拟:模拟端口8888
???Socket clientSocket = new Socket("localhost", 8888);
???//得到服务器输入流
???InputStream inData = clientSocket.getInputStream();
???//建立输出流至服务器
???OutputStream outData = clientSocket.getOutputStream();
???//发送输出流
???PrintWriter toServer = new PrintWriter(outData, true);
???//键盘输入扫描
???Scanner scanner = new Scanner(System.in);
???//服务器输入扫描
???Scanner data = new Scanner(inData);
???//得到服务器第一行输入信息
???String heading = data.nextLine();
???//打印信息
???System.out.println(heading);
???//键盘输入循环
???while(scanner.hasNextLine()){
????//得到键盘输入信息
????String line = scanner.nextLine();
????//传送至服务器
????toServer.println(line);
????//得到服务器回答信息
????String fromServer = data.nextLine();
????//打印信息
????System.out.println(fromServer);
????if(fromServer.equals("Bye!")){
?????System.out.println("Now is disconnection...");
?????break;
????}
???}
???clientSocket.close();
??} catch (UnknownHostException e) {
???e.printStackTrace();
??} catch (IOException e) {
???e.printStackTrace();
??}

?}

}

服务端:

????????? public class ServerSocketTest {

?public static void main(String[] args) {
??System.out.println("Welcome the server is running...");
??try {
???//服务器监听端口
???ServerSocket serverSocket = new ServerSocket(8888);
???//接受客户端连接
???Socket fromClient = serverSocket.accept();
???System.out.println("Connection to the client...");
???//得到客户端输入流
???InputStream inData = fromClient.getInputStream();
???//得到客户端输出流
???OutputStream outData = fromClient.getOutputStream();
???//创建输出流
???PrintWriter toClient = new PrintWriter(outData, true);
???toClient.println("Type quit to STOP");
???//客户端输入扫描
???Scanner sc = new Scanner(inData);
???//
???while(sc.hasNextLine()){
????//得到客户端输入信息
????String line = sc.nextLine();
????if(line.equalsIgnoreCase("quit")){
?????serverSocket.close();
?????toClient.println("Bye!");
?????break;
????}
????toClient.println(line.toUpperCase());
???}
??} catch (IOException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??}
?}
}

  相关解决方案