很简单的聊天窗口,不能建立连接。郁闷啦
源程序是这样的:import java.awt.*;
import java.awt.event.*;
import
import
import
import
import
import java.util.Scanner;
import javax.swing.*;
public class ChatClient extends JFrame implements ActionListener {
private JButton jbtSend,jbtExit;
private JTextField jtfTxt1;
private JTextArea jtaArea;
private JLabel jlfLabel;
private JPanel p1,p2;
public ChatClient()
{
super("Chat Client");
p1 = new JPanel();
p2 = new JPanel();
jtaArea = new JTextArea(8,37);
JScrollPane pane = new JScrollPane(jtaArea);
jtaArea.setEditable(false);
jtfTxt1 = new JTextField(20);
jbtSend = new JButton("发送");
jbtExit = new JButton("退出");
jlfLabel = new JLabel("请输入:");
p1.add(jtaArea);
p2.add(jlfLabel);
p2.add(jtfTxt1);
p2.add(jbtSend);
p2.add(jbtExit);
setLayout(new FlowLayout());
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.SOUTH);;
jtfTxt1.addActionListener(this);
jbtSend.addActionListener(this);
jbtExit.addActionListener(this);
setVisible(true);
setSize(420, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if(command.equals("发送"))
{
try
{
Socket socket = new Socket("localhost",4700);
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os = new PrintWriter(socket.getOutputStream());
Scanner sc = new Scanner(System.in);
jtaArea.setText("客户:");
String line = sc.nextLine();
while(!line.equals("bye"))
{
os.println(line);
os.flush();
jtaArea.setText("服务器:"+is.readLine()+"\n");
jtaArea.setText("客户:");
line = sc.nextLine();
}
sc.close();
os.close();
is.close();
socket.close();
}
catch (IOException ex)
{
System.out.println("ERROR:"+ex);
}
}
else if(command.equals("退出"))
System.exit(0);
}
public static void main(String[] args){
ChatClient client = new ChatClient();
}
}
如图示:
可惜 我运行之后提示 ERROR: Connection refused: connect
因为是自觉,所以不知道错误怎么解决。在线等