一个简单的聊天程序,谁知道哪里错了,谢了
这个是服务端import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import
import *;
import
import
import javax.imageio.IIOException;
import javax.swing.*;
public class server extends JFrame implements ActionListener {
JTextField text;
JTextArea area;
InputStream in;
OutputStream out;
public server() throws IOException {
setTitle("服务机");
text = new JTextField(20);
text.setBounds(10, 10, 270, 30);
JPanel p = new JPanel();
area = new JTextArea(30, 30);
area.setBackground(Color.cyan);
p.add(text);
text.addActionListener(this);
p.add(new JLabel("发送"));
add("North", p);
add("Center", area);
setVisible(true);
setSize(400, 400);
try {
ServerSocket server = new ServerSocket(400);
Socket client = server.accept();
area.append("已连接到客户机" + client.getInetAddress().getLocalHost());
in = client.getInputStream();
out = client.getOutputStream();
} catch (IIOException e) {
}
while (true) {
byte[] buf = new byte[128];
in.read(buf);
area.setText("客户机说" + new String(buf) + "\n");
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == text) {
String s = text.getText();
area.append("服务机说:" + s + "\n");
try {
out.write(s.getBytes());
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
new server();
}
}
这个是客户端
import java.awt.Color;
import java.awt.event.*;
import *;
import *;
import javax.imageio.IIOException;
import javax.swing.*;
public class Client extends JFrame implements ActionListener {
JPanel p;
JTextField text;
JTextArea area;
InputStream in;
OutputStream out;
public Client() throws UnknownHostException, IOException {
setTitle("客户机");
text = new JTextField(20);
text.setBounds(10, 10, 270, 30);
JPanel p = new JPanel();
area = new JTextArea(30, 30);
area.setBackground(Color.cyan);
text.addActionListener(this);
p.add(text);
p.add(new JLabel("发送"));
add("North", p);
add("Center", area);
setVisible(true);
setSize(400, 400);
try {
Socket client = new Socket("127.127.0.0", 400);
in = client.getInputStream();
out = client.getOutputStream();
area.append(" 服务器为:" + client.getInetAddress().getHostName()
+ "\n");
} catch (IIOException e) {
}
while (true) {
try {
byte buf[] = new byte[256];
in.read(buf);
area.setText("服务器说" + new String(buf) + "\n");
} catch (IIOException e0) {
}
}
}
public static void main(String[] args) {
try {
Client e = new Client();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void actionPerformed(ActionEvent a) {
if (a.getSource() == text) {
String st;
st = text.getText();
area.append("客户机说" + st + "\n");
try {
out.write(st.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}