首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

求教编程有关问题

2013-01-23 
求教编程问题编了一个聊天系统的雏形目前问题是在向客户端输入字符时,服务器端没输出同样的字符编译是没错

求教编程问题
编了一个聊天系统的雏形  目前问题是在向客户端输入字符时,服务器端没输出同样的字符   编译是没错的
求大家帮我看看什么地方错了
客户端
package njyd.dsy.chat;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class ChatClient extends Frame{

DataOutputStream dos = null;
Socket s = null;
TextField tfText = new TextField();
TextArea taContent = new TextArea();
public static void main(String[] args) {
new ChatClient().launchFrame();
}

public void launchFrame() {
setLocation(300,300);
setSize(500,500);
add(tfText,BorderLayout.SOUTH);
add(taContent,BorderLayout.NORTH);
pack();
this.addWindowListener( new WindowAdapter() {


@Override
public void windowClosing(WindowEvent e) {
disconnect();
System.exit(0);
}

});
tfText.addActionListener(new TFListener());
setVisible(true);
connect();
}

public void disconnect() {
try {
dos.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public void connect() {
try {
s = new Socket("127.0.0.1",8888);
            dos = new DataOutputStream(s.getOutputStream());
System.out.print("a Server connected");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private class TFListener implements ActionListener{  /*响应enter 输入字符  */

@Override
public void actionPerformed(ActionEvent e) {
String str = tfText.getText().trim();
taContent.setText(str);
tfText.setText("");

try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}


}
}
服务器端
package njyd.dsy.chat;

import java.io.*;
import java.net.*;

public class ServerChat {

public static void main(String[] args) {
 boolean started = false;
 DataInputStream dis = null;
 ServerSocket ss = null;
 Socket s = null;
 try {
ss = new ServerSocket(8888);
 } catch(BindException e){
 System.out.println("端口使用中");
 } catch(IOException e){
 e.printStackTrace();
 }
 
 try{
 started = true;
    while(started) {
    boolean flag = false;
    s = ss.accept();
System.out.print("a Client connected!");
                    flag = true;
                    dis = new DataInputStream(s.getInputStream());
                    while(flag) {


                    String str =  dis.readUTF();
                    System.out.println(str);
                    }
                    dis.close();
                    }
    } catch(EOFException e){
                  System.out.println("Client closed"); 
    } catch(IOException e) {
    e.printStackTrace();
    }finally{
    try{
    if(dis !=null) dis.close();
    if(s != null) s.close();
    }catch(IOException e1){
    e1.printStackTrace();
    }
    }
     }
}
编程 socket
[解决办法]

引用:
我不知道怎么回复楼上    我在服务器编了个让接受到的信息打印出来的数据程序   可是我在运行的时候却没有这个功能
点击引用就可以了,我就可以收到系统的提醒

热点排行