帮我把单线程的程序改成多线程JAVA,急!
发布网友
发布时间:2023-08-18 00:10
我来回答
共1个回答
热心网友
时间:2024-01-25 03:00
自定义一个线程类或者一个Runnable类。。
并定义一个socket类型的属性。。
构造方法接受一个socket类型的参数。。对socket属性用他来初始化。。
然后这个地方。。
Client=server.accept( );
Thread thread=new Thread(Client);//把获得的客户端socket穿进去。。
thread.start();
然后在你自定义的线程或者Runnable类里面的run方法写上你想用那个socket做的事就行了。。这样与每个客户端的通信即socket都是一个单独的线程了。。
给你改了下哈。。可能不对哈。。反正你按照那个思路改的话肯定没问题的。。
package java07_25;
import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer extends Frame implements ActionListener {
Label label = new Label("输入聊天信息,按回车发送!");
TextField tf = new TextField(20);
TextArea ta = new TextArea();
Panel panel = new Panel();
ServerSocket server;
Socket Client;
InputStream DataIn;
OutputStream DataOut;
public SocketServer() {
super("服务器 ");
setSize(380, 300);
panel.add(label);
panel.add(tf);
tf.addActionListener(this);
add("North", panel);
add("Center", ta);
ta.setBackground(Color.black);
ta.setForeground(Color.yellow);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
show();
try {
server = new ServerSocket(5000);
while (true) {
Client = server.accept();
Thread thread = new Thread(new SSocket(Client));
thread.start();
}
} catch (IOException ioe) {
}
}
public static void main(String args[]) {
new SocketServer();
}
public void actionPerformed(ActionEvent e) {
try {
String str = new String(tf.getText());
byte buf[] = str.getBytes();
tf.setText(" ");
DataOut.write(buf);
ta.append("服务器说:" + str + "\n");
} catch (IOException ioe) {
}
}
class SSocket implements Runnable {
Socket client;
public SSocket(Socket client) {
this.client = client;
}
public void run() {
DataInputStream input;
while (true) {
try {
ta.append("已经和客户机连接:" + client.getInetAddress()
+ client.getInetAddress().getHostName() + "\n\n");
DataIn = client.getInputStream();
DataOut = client.getOutputStream();
byte buff[] = new byte[512];
DataIn.read(buff);
String str = new String(buff);
ta.append("客户机说:" + str + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}