一,在tcp两台计算机数据交互过程中注意:
1)同一次交互过程中的socket对象是同一个;
2)使用Bufferedread读取数据时没有换行市会等待在下列代码中体现的问题就是服务器反馈给客户端的语句,客户端收不到.服务器端反馈回来的语句必须有换行标识.
[Java] 纯文本查看 复制代码 package zixilianxitcp;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class LiaoTianKeHuDuan {
public static void main(String[] args) throws IOException {
Socket s = new Socket("127.0.0.1", 10000);
Scanner sc = new Scanner(System.in);
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader bfr = new BufferedReader(new InputStreamReader(s.getInputStream()));
//String str;
// while ((str = br.readLine()) != null) {
// if ("886".equals("str")) {
// bw.write(str);
// break;
// }
// bw.write(str);
// bw.newLine();
// bw.flush();
while (true) {
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String s2 = sc.next();
if ("886".equals(s2)) {
bw.write(s2);
break;
}
bw.write(s2);
bw.newLine();
bw.flush();
String s1 = bfr.readLine();
if (s1.equals("886")) {
System.out.println("服务器端已结束");
s.close();
}
System.out.println("服务器:" + s1);
}
}
}
package zixilianxitcp;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class LiaoTianFuWuQiDuan {
public static void main(String[] args) throws IOException {
ServerSocket ss=new ServerSocket(10000);
Scanner sc=new Scanner(System.in);
Socket s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bfw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
while (true) {
String str = br.readLine();
if ("886".equals(str)) {
System.out.println("客户端已退出");
ss.close();
break;
}
System.out.println("客户端: "+str);
String next = sc.nextLine();
bfw.write(next);
bfw.newLine();
bfw.flush();
if ("886".equals(next)){
bfw.close();
ss.close();
break;
}
}
}
} |