日期:2014-05-20  浏览次数:20972 次

java聊天程序的问题..请大侠们帮帮小弟...
一个Client客户端,一个Server服务器端...

在数据输入及输出的时候出了问题...自己找了好久都找不到...

输出流用的是bufferedWriter...   输入流用的是BufferedReader...

最后运行的时候数据无法相互发送...

但是用ObjectInputStream和ObjectOutputStream()分别替换I/0又可以了..

下面是两个类的源代码...

public   TestClient(String   host){
chatServer   =   host;
Container   container   =   getContentPane();
inputInfo   =   new   JTextField();
inputInfo.setEnabled(false);
inputInfo.addActionListener(new   ActionListener   (){
public   void   actionPerformed(ActionEvent   e){
sendData(e.getActionCommand());
inputInfo.setText( " ");
}

});

container.add(inputInfo,java.awt.BorderLayout.NORTH);
showingInfo   =   new   JTextArea();
container.add(new   JScrollPane(showingInfo),BorderLayout.CENTER);
setSize(400,300);
setTitle( "Client ");
setVisible(true);
}

public   void   run(){
connectToServer();
getStream();
processConnect();
close();

}
public   static   void   main(String[]   args)   {
TestClient   client;
if   (args.length   ==   0){

client   =   new   TestClient( "127.0.0.1 ");
}
else{
client   =   new   TestClient(args[0]);
}
client.setDefaultCloseOperation(client.EXIT_ON_CLOSE);
client.run();
}

public   void   connectToServer(){
showingInfo.setText( "connection...\n ");
try   {
client   =   new   Socket(InetAddress.getByName(chatServer),5000);
showingInfo.append(
"Connecting   to   "+client.getInetAddress().getHostName());
}   catch   (UnknownHostException   e)   {

System.out.println( "不知名主机. ");
}   catch   (IOException   e)   {
System.out.println( "输入输出流异常 ");
e.printStackTrace();
}

}
public   void   getStream(){

try   {
os   =   new   BufferedWriter(   new   OutputStreamWriter(client.getOutputStream()));
os.flush();
is   =   new   BufferedReader   (new   InputStreamReader(client.getInputStream()));
showingInfo.append( "\ngot   I/O   Streams ");

}   catch   (IOException   e)   {
System.out.println( "输入输出流异常 ");
e.printStackTrace();
}
}
public   void   processConnect(){
inputInfo.setEnabled(true);
String   message;
try   {

do{
message   =   (String)   is.readLine();

showingInfo.append( "\n "+message);
showingInfo.setCaretPosition(showingInfo.getText().length());
}while(!   message.equals( "SERVER> > > terminate "));


}   catch   (EOFException   e){
System.out.println( "EOFError ");
}     catch   (IOException   e)   {
System.out.println( "输入输出流异常 ");
e.printStackTrace();
}
}
public   void   sendData(String   message){
try   {
os.write( "CLIENT> > > "+message);
os.flush();
showingInfo.append( "\nCLIENT> > > "+message);