import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;public class ChatClient extends JFrame {
public static void main(String[] args) {
new ChatClient().chatJFrame(); } JTextArea jta;
JTextField jtf;
Socket s=null;
DataOutputStream dos=null;
public void chatJFrame() {
this.setSize(400, 300);
this.setLocationRelativeTo(null);
// this.setDefaultCloseOperation(this.EXIT_ON_CLOSE); Container c = this.getContentPane();
c.setLayout(null); jta = new JTextArea();
JScrollPane jsp = new JScrollPane(jta);
jsp.setBounds(10, 10, 200, 200);
c.add(jsp); jtf = new JTextField();
jtf.setBounds(210, 210, 100, 20);
jtf.addActionListener(new TFlistener());
c.add(jtf); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {
disConnect();
System.exit(0);
}
}); this.setVisible(true);
connect();
} public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
} catch (UnknownHostException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
} }
public void disConnect(){
try {
dos.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class TFlistener implements ActionListener { public void actionPerformed(ActionEvent e) {
String str = jtf.getText().trim();
jta.setText(str);
jtf.setText(""); try {
// while(!(str.equals("bye"))){
System.out.println("Client say" +" "+ str);
dos.writeUTF(str);
dos.flush();
// } } catch (IOException e1) { e1.printStackTrace();
}
} }
}
import java.io.*;
import java.net.*;
public class ChatServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8888);
while(true){
Socket s =ss.accept();
DataInputStream dis = new DataInputStream(
s.getInputStream());
System.out.println(dis.readUTF());
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}}报出SocketException异常
在客户端的dos.writeUTF(str);那行,我是照别人代码打的,经过细心比较后,除了我用的是JFrame,他用的是Fram外,其他都是一样,请高手改下,感激不尽
解决方案 »
- 急急急啊,急啊,myeclipse用jdbc方式连好程序了,生成的
- 怎样使代码中单引号'能update进数据库
- 一个初学boolean容易忽视的问题。
- Integer i = new Integer("0x10");封装器问题
- 中序表达式求值问题,请大家分析分析,结果不正确~~~
- 一个很不错的学习资料网站,有很多教学视频资料下载,晚了就没了.
- 各位好,我想问一下,select后的sql数据库的一堆记录怎样显示在面板上呢?
- jar打包的applet 启动后,class文件放在哪里?
- 类的一点疑问!!请指教!!
- 大家别见笑,我来问一个极菜的问题,java到底是一门什么语言?
- 返回一个字段的值|*|*|*|*|*|*|
- 请教一个正则表达式的写法?
public class TFlistener implements ActionListener { public void actionPerformed(ActionEvent e) {
String str = jtf.getText().trim();
jta.setText(str);
jtf.setText(""); try {
// while(!(str.equals("bye"))){
System.out.println("Client say" +" "+ str);
dos.writeUTF(str);
dos.flush();
// } } catch (IOException e1) { e1.printStackTrace();
}
} }没有定义button 直接回车就可以把信息传递给jta,已经定义了一个监听器的!!
dis.close();
...
读了一次就关闭了流??楼主是不是在客户端多次发送数据啊,那就肯定会抛异常了,因为无论writeUTF和readUTF都是阻塞式的。
如果是这个问题,只要不要在这里关闭流即可。一般也不要在这样的地方关闭,不严谨。