//客户端代码
import java.io.*;
import java.net.*;
public class TalkClient{
public static void main(String[] args) throws Exception{
//定义连接服务器的socket流Socket s = new Socket("192.168.1.103",9999);//获取socket流中的输入流DataInputStream disNet = new DataInputStream(s.getInputStream());//获取socket流中的输出流DataOutputStream dosNet = new DataOutputStream(s.getOutputStream());//接收命令行的输入流BufferedReader brLocalIn = new BufferedReader(new InputStreamReader(System.in));//这里用到转换流,原因是因为BufferedReader 构造方法接收Reader类型的参数
//定义结束服务器信息的字符串变量String serverIn = null;//向服务器端发送系统输入的信息,并打印到屏幕//定义接收向服务器发送信息的字符串变量String clientOut=null;//从系统输入读取信息,并发送给服务器端clientOut = brLocalIn.readLine();dosNet.writeUTF(clientOut);//从服务器端接收数据,并打印到屏幕//serverIn = disNet.readUTF();//System.out.println(" server:" + serverIn);//循环判断执行条件,满足条件执行以下语句/*这里循环判断比较重要的一点,是判断条件是什么,应该如何组织内部语句的顺序很明显,我这里需要判断是系统是否有数据录入,如果有,将执行语句,而不是判断系统是否从客户端读取到数据,这是次要判断*/serverIn = disNet.readUTF();System.out.println(" server:" + serverIn);//clientOut = brLocalIn.readLine();//dosNet.writeUTF(clientOut);
while(!clientOut.equals("bye")){//这里循环判断的条件应该判断的是brLocalIn.readLine()!="bye"
//获取系统输入发送给服务器端,并打印到屏幕dosNet.writeUTF(clientOut);System.out.println(" client " + clientOut);//从服务器端接收消息并打印System.out.println(" server:" + disNet.readUTF());clientOut = brLocalIn.readLine();
}
}
}
//服务器端代码import java.io.*;import java.net.*;public class TalkServer{
public static void main(String[] args) throws Exception{
//创建服务器端监听端口ServerSocket ss = new ServerSocket(9999);//创建用于连接客户端的socket流Socket s = ss.accept();System.out.println("a client is connected,waiting for an answer");//创建接收系统输入的缓冲流BufferedReader brLocalIn = new BufferedReader(new InputStreamReader(System.in));//创建socket流的输入流DataInputStream disNet = new DataInputStream(s.getInputStream());//创建socket流的输出流DataOutputStream dosNet = new DataOutputStream(s.getOutputStream());//创建用于接收客户端消息的字符串变量String clientIn =null;//创建用发送到客户端的字符串变量String serverOut=null;//从客户端接收数据,并打印到屏幕//clientIn = disNet.readUTF();//System.out.println(" client:" + clientIn);//从系统获取本机输入的数据,并发送给客户端//serverOut = brLocalIn.readLine();//dosNet.writeUTF(" server:" + serverOut);//循环判断输系统输入是否等于byeclientIn =disNet.readUTF();System.out.println(" client:"+clientIn);serverOut = brLocalIn.readLine();dosNet.writeUTF(serverOut);while(!serverOut.equals("bye")){
//接收系统输入的信息,打印到屏幕,并发送至客户端,serverOut = brLocalIn.readLine();dosNet.writeUTF(serverOut);System.out.println(" server:" + serverOut);//接收客户端通过socket流发送过来的消息并打印到屏幕clientIn = disNet.readUTF();System.out.println(" client:" + clientIn);
}
}
}
总结:
1、出现错误提示,非法字符,与是否为英文状态下输入字符有关
2、判断是否结束对话用的第一种方法 clientOut!="bye" 不能结束对话,因为直接比较两个字符串是比较它们的地址,所以这里需要用equals方法
3、readLine 与 readUTF都为阻塞式方法,所以在写程序时,需要避免两边都在读的情况发生
4、使用tcp连接不适合做聊天程序,必须是你来我往的方式发送数据,很让人崩溃
5、注意使用flush()
6、注意关闭使用的资源