這是個我們上課用的老師的客戶端,學生的讓我給弄丟了 但你仿照這個可以的我相信你
package Study;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class AllServer extends JFrame implements ActionListener,Runnable{
ServerSocket server = null;
Socket socket = null;
DataInputStream dis = null;
DataOutputStream dos = null;
BufferedReader br = null;
JTextArea ta=new JTextArea(5,15);
JTextField txt=new JTextField(10);
JPanel panel=new JPanel();
JButton but=new JButton("發送");
JScrollPane spanel=new JScrollPane(ta);
Vector v=null;
AllServer(){
this.setTitle("伺服器窗口");
but.addActionListener(this);
txt.addActionListener(this);
panel.add(spanel);
panel.add(txt);
panel.add(but);
this.setDefaultCloseOperation(3);
this.getContentPane().add(panel);
this.setBounds(100,300,200,200);
this.setVisible(true);
}
// 創建伺服器
public void initServer() {
try {
v=new Vector();
server = new ServerSocket(6789);
this.ta.append("伺服器啟動成功\n");
while(true){
socket = server.accept();
v.add(server);
this.ta.append("一個客戶端聯接成功\n");
}
}
catch (IOException e) {
e.printStackTrace();
}
// br = new BufferedReader(new InputStreamReader(System.in));
}// 發送信息
public void sendMsg(String msg,Socket socket,int j) {
try {
DataOutputStream dos=new DataOutputStream(socket.getOutputStream());
dos.writeUTF(msg);
dos.flush();
this.ta.append("伺服器:"+msg+"\n");
}
catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
String msg = null;
try {for(int i=0;i<v.size();i++){
Socket scoket=(Socket) v.get(i);
DataInputStream dis=new DataInputStream(scoket.getInputStream());
msg=dis.readUTF();
for(int j=0;j<v.size();j++){
this.sendMsg(scoket.getInetAddress().getHostAddress()+":"+msg,(Socket)v.get(j),j);
}
while(true){
msg = dis.readUTF();
this.ta.append("客戶端:"+msg+"\n");
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
AllServer ts = new AllServer();
ts.initServer();
// 初始化
}
public void actionPerformed(ActionEvent arg0) {
String s=txt.getText();
}
}