本帖最后由 Teemo_Mann 于 2014-4-16 19:07 编辑
为什么我的客户端输入一次之后,再输一次就没反应了
帮忙看下
Client端
- package com.itheima;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintStream;
- import java.net.InetAddress;
- import java.net.Socket;
- import java.util.Scanner;
- public class Test10Client {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
-
- Socket socket = null;
-
- try {
-
- //创建Socket, 用于和客户端建立连接
- socket = new Socket("127.0.0.1", 1234);
- while(true){
- BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- PrintStream ps = new PrintStream(socket.getOutputStream());
-
- //Scanner用于接收用户控制台输入
- Scanner scanner = new Scanner(System.in);
- System.out.println("请输入一个字符串:");
- String line = scanner.nextLine();
-
- ps.println(line); // 发送到服务端
- System.out.println(br.readLine()); // 读取服务端发回的字符串并进行 打印
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally{
- if(socket != null){
- try {
- socket.close();
- } catch(IOException e){
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- }
复制代码
Server端
- package com.itheima;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintStream;
- import java.net.ServerSocket;
- import java.net.Socket;
- /**
- * 使用TCP协议完成一个客户端一个服务器。客户端从键盘输入读取一个字符串,发送到服务器。
- 服务器接收客户端发送的字符串,反转之后发回客户端。客户端接收并打印。
- *
- *
- */
- public class Test10 {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
-
- Socket socket = null;
- try {
- ServerSocket serverSocket = new ServerSocket(1234);
- while(true){
- //创建绑定端口1234的对象ServerSocket
-
- socket = serverSocket.accept();//接收客户端请求,若有客户端请求,则连接并创建Socket
- BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));//创建带缓冲的字符读入流
- String sr = br.readLine();//读取客户端发送过来的消息
- PrintStream ps = new PrintStream(socket.getOutputStream());
- ps.println(new StringBuffer(sr).reverse());//将反转后的字符串发送给客户端
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally{
- if(socket != null){
- try {
- socket.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- }
复制代码 |