Socket 编程的初级问题
package Chat;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Client extends Frame implements ActionListener{
Panel p = new Panel();
Panel p1 = new Panel();
TextArea ta = new TextArea(5, 20);
Button btn = new Button("Send");
Button btn_conn = new Button("Connect");
Label lbl_ip = new Label("IP :");
Label lbl_port = new Label("Port :");
TextField t_ip = new TextField("ms-p4",15);
TextField t_port = new TextField("6666",10);
private String ip,port;
ObjectInputStream input;
ObjectOutputStream output;
Socket connection;
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btn_conn)
if(this.Connect())
{
new myThread().run();
}
else
return;
if(e.getSource()==btn)
this.sendMes();
}
public Client() {
super("Client");
p.add(lbl_ip);
p.add(t_ip);
p.add(lbl_port);
p.add(t_port);
btn_conn.addActionListener(this);
p.add(btn_conn);
this.setLayout(new BorderLayout());
this.add(p,BorderLayout.NORTH);
p1.add(new JScrollPane(ta));
p1.add(btn);
this.add(p1,BorderLayout.CENTER);
btn.addActionListener(this);
this.setSize(400,300);
this.setVisible(true);
}
public void sendMes()
{
try
{
output.writeObject(this.ta.getText());
output.flush();
ta.setText("");
ta.requestFocus();
}
catch(Exception e){JOptionPane.showMessageDialog(null,"Send message wrong!");}
}
public boolean Connect()
{
try{
connection = new Socket(t_ip.getText(), Integer.parseInt(t_port.getText()));
//JOptionPane.showMessageDialog(null, "Connect Successfully!");
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
return true;
}
catch(Exception e)
{
System.out.println(e.toString());
return false;
}
}
public void begin()
{
try {
connection = new Socket("ms-p4", 6666);
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
String message = "";
while (true) {
if (input != null)
{
message = (String) input.readObject();
ta.append("\nClient has received this client's message:");
this.ta.append("\n" + message );
ta.setCaretPosition(ta.getText().length());
}
}
}
catch (Exception e) {
//JOptionPane.showMessageDialog(null, "服务器未打开或已经关闭!");
}
}
public static void main(String args[]) {
Client client = new Client();
client.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
class myThread extends Thread{
public void run()
{
String message = "";
try{
while (true) {
if (input != null) {
message = (String) input.readObject();
ta.append("\nClient has received this client's message:");
ta.append("\n" + message);
ta.setCaretPosition(ta.getText().length());
}
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"an error accurred while listening.");
}
}
}
}
当客户端与server正常建立链接后,就如同死机了,我知道是进入了死循环,但如何将这个循环函数放进另外一个线程里面执行?