I have read a lot about multithread client but for this one,I can not make it multithread! would you please help me?
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);
}
}
}
also active method will be called when the client write something on the text area and then clicks on the send button.
2) also i have a question that:
in the other class I have this action performed for my send button,does it mean that client is multithread??
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 开发者_如何学Python
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();
}
Last EDIT:
this is my active method:
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();
}
short answer: YES. The code in the second snippet would create a new thread everytime the method jButton1ActionPerformed is called.
I am not sure if this is the intended behavior though.
does it mean that client is multithread??
Multithreading is the use of more than one thread. Technically yes you are multithreading.
So ,can I run 2 clients at the same time?
Short answer, Yes.
Long answer, you will need to make sure your methods are thread-safe and the MainCient
is not blocking or being blocked by any other thread.
When Multithreading, i usually tend to make a centralized class to control the "pool" of Threads. I call it the Dispatcher. Which manages a map of threads.
精彩评论