我已经阅读了很多关于多线程客户端的内容,但是对于这个,我无法使它成为多线程的! 你能帮我吗?如何将此客户端作为多线程客户端?
public class MainClient implements Runnable{
private static InformationClass info = new InformationClass();
private static Socket c;
private static String text;
public static String getText() {
return text;
}
public static void setText(String text) {
MainClient.text = text;
}
private static PrintWriter os;
private static BufferedReader is;
static boolean closed = false;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
MainFrame farme = new MainFrame();
farme.setVisible(true);
try {
c = new Socket("localhost", 5050);
os = new PrintWriter(c.getOutputStream(), true);
is = new BufferedReader(new InputStreamReader(c.getInputStream()));
} catch (UnknownHostException ex) {
Logger.getLogger(MainClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void active() {
String teXt = MainClient.getText();
System.out.println(teXt);
os.println(teXt);
try {
String line = is.readLine();
System.out.println("Text received: " + line);
os.flush();
is.close();
is.close();
c.close();
} catch (IOException ex) {
Logger.getLogger(MainClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
当客户端在文本区域上写入内容然后单击发送按钮时,也会调用活动方法。
2)我也有一个问题:
在其他类我有这个动作我的发送按钮进行,这是否意味着客户端是多线程?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
new Thread(new Runnable() {
@Override
public void run() {
// This gets run in a background thread
String text = jTextArea1.getText();
jTextArea2.append(client.getCurrentName() + " : " + text + "\n");
MainClient.setText(client.getCurrentName() + " : " + text + "\n");
clear();
MainClient.active();
}
}).start();
}
最后编辑:
这是我的主动方法:
public static void active() {
String teXt = MainClient.getText();
os.println(teXt);
String line = is.readLine();
System.out.println("Text received: " + line);
os.flush();
is.close();
is.close();
c.close();
}
那么,我可以同时运行2个客户吗? – Johanna 2010-01-18 06:21:15
@Johanna,您可能需要更清楚地指定要求以获得完整答案。你打算做什么? – Rahul 2010-01-18 06:34:52
我想使我的程序一次运行2个或更多的客户端。我已经了解到我们应该让我们的客户端类(其中有套接字) 实现可运行接口,但我想知道,如果没有这样做,我们可以有这样的这个动作执行了为我们做的发送按钮吗? – Johanna 2010-01-18 06:43:30