各位高手,现在想求一程序,就是实现服务器和客户端互相通信,既一个服务器可以有多个客户端连接,服务可以发消息给客户端,客户端也可以发消息给服务器,并且可以互相收到对方发送的消息。
先谢谢啦,问题解决立刻解贴!
先谢谢啦,问题解决立刻解贴!
解决方案 »
- 定时器刷新问题,求帮助
- 求助各位高手,我实在不行了,关于网页数据下载,有一万多页!
- 问个关于UML的问题
- 编译2个错误
- 编译出错,用JBuilder编译,它出现找不到init<>方法,这是什么错误????
- 一个目录树的父子节点有4千多或更多,现在用以前的XTREE代码出现了读取树结构读取不出的错误.请问用什么比较好,对于数据量较大的数据量的
- 菜鸟求助java问题,
- 大家好啊,我学JAVA没有多久,想和大家共同学习进步,有意者,留下QQ,MSN,我的QQ70129571,MSN:[email protected]
- 在applet中打開一個Frame,如何讓它位于屏幕中央?
- jdk Standard version vs Enterprise version,有什么区别?
- 应用程序添加声音代码不响
- java cookie的不生成疑问
import java.net.*;
import java.util.*;public class ChatServer {
boolean started = false;
ServerSocket ss = null;
List<Client> clients = new ArrayList<Client>();
public static void main(String[] args) {
new ChatServer().start();
}
public void start() {
try {
ss = new ServerSocket(8888);
started = true;
} catch (BindException e) {
System.out.println("端口使用中....");
System.out.println("请关掉相关程序并重新运行服务器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
try {
while(started) {
Socket s = ss.accept();
Client c = new Client(s);
System.out.println("a client connected!");
new Thread(c).start();
clients.add(c);
//dis.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("对方退出了!我从List里面去掉了!");
//e.printStackTrace();
}
}
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
System.out.println(str);
for(int i=0; i<clients.size(); i++) {
Client c = clients.get(i);
c.send(str);
//System.out.println(" a string send !");
}
/*
for(Iterator<Client> it = clients.iterator(); it.hasNext(); ) {
Client c = it.next();
c.send(str);
}
*/
/*
Iterator<Client> it = clients.iterator();
while(it.hasNext()) {
Client c = it.next();
c.send(str);
}
*/
}
} catch (EOFException e) {
System.out.println("Client closed!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(dis != null) dis.close();
if(dos != null) dos.close();
if(s != null) {
s.close();
//s = null;
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}客户端代码:import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false; TextField tfTxt = new TextField(); TextArea taContent = new TextArea();
Thread tRecv = new Thread(new RecvThread()); public static void main(String[] args) {
new ChatClient().launchFrame();
} public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() { @Override
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("192.168.1.110", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
/*
try {
bConnected = false;
tRecv.join();
} catch(InterruptedException e) {
e.printStackTrace();
} finally {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
*/
}
private class TFListener implements ActionListener { public void actionPerformed(ActionEvent e) {
String str = "李成龙:" + tfTxt.getText().trim();
//taContent.setText(str);
tfTxt.setText("");
try {
//System.out.println(s);
dos.writeUTF(str);
dos.flush();
//dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable { public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
//System.out.println(str);
taContent.setText(taContent.getText() + str + '\n');
}
} catch (SocketException e) {
System.out.println("退出了,bye!");
} catch (EOFException e) {
System.out.println("推出了,bye - bye!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
private Set<ChatServerThread> threadSet = new HashSet<ChatServerThread>();
private BlockingDeque<String> deque = new LinkedBlockingDeque<String>(5);
public void removeThread(ChatServerThread thread) {
threadSet.remove(thread);
}
public void addMessage(String msg) {
try {
System.out.println("<< " + msg);
deque.putFirst(msg);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
new ChatServer().start();
}
public void start() {
try {
ss = new ServerSocket(7000);
started = true;
} catch (BindException e) {
System.out.println("无法启动服务器:端口被占用");
} catch (IOException e) {
System.out.println("无法启动服务器:" + e.getLocalizedMessage());
}
try {
Thread thread = null;
new ChatServerBroadcast(threadSet, deque).start();
while (started) {
Socket socket = ss.accept();
System.out.println("a client connected");
ChatServerThread c = new ChatServerThread(this, socket);
thread = new Thread(c);
c.setThreadId(thread.getId());
threadSet.add(c);
thread.start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
public class ChatServerThread implements Runnable {
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
boolean bconnected = false;
private long threadId;
public long getThreadId() {
return threadId;
}
public void setThreadId(long threadId) {
this.threadId = threadId;
}
private ChatServer server = null;
ChatServerThread(ChatServer server, Socket s) {
this.server = server;
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bconnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
while (bconnected) {
server.addMessage(dis.readUTF());
}
} catch (EOFException e) {
System.out.println("Client closed!");
} catch (IOException e) {
e.printStackTrace();
} finally {
server.removeThread(this);
try {
if (dis != null)
dis.close();
if (s != null)
s.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public void sendMessage(String msg) {
try {
dos.writeUTF(msg);
} catch (Exception ex) {
bconnected = false;
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (threadId ^ (threadId >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ChatServerThread other = (ChatServerThread) obj;
if (threadId != other.threadId)
return false;
return true;
}
}
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
/**
* 负责群发消息到各个连接
*
* @author Administrator
*
*/
public class ChatServerBroadcast extends Thread {
private Set<ChatServerThread> threadSet;
private BlockingDeque<String> deque;
ChatServerBroadcast(Set<ChatServerThread> threadSet, BlockingDeque<String> deque) {
this.threadSet = threadSet;
this.deque = deque;
}
public void run() {
while (true) {
try {
String msg = deque.takeLast();
System.out.println(">> " + msg);
Iterator<ChatServerThread> it = threadSet.iterator();
while (it.hasNext()) {
it.next().sendMessage(msg);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
class ChatClient extends Frame {
private static final long serialVersionUID = -6290371526617318074L;
public static void main(String[] args) {
new ChatClient("chat");
}
Button b = new Button("send");
Socket s = null;
DataOutputStream dos = null;
TextField tf = new TextField();
TextArea ta = new TextArea();
DataInputStream dis = null;
boolean bconnected = false;
ChatClient(String s) {
super(s);
setLocation(400, 300);
setVisible(true);
setSize(300, 300);
setLayout(new BorderLayout());
add("East", b);
Monitor1 monitor = new Monitor1();
b.addActionListener(monitor);
tf.addKeyListener(monitor);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
disconnected();
System.exit(0);
}
});
add("South", tf);
add("North", ta);
pack();
connect();
new Thread(new RecvThread()).start();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 7000);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("connected");
bconnected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnected() {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class Monitor1 extends KeyAdapter implements ActionListener, KeyListener {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
doSend();
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b) {
doSend();
}
}
private void doSend() {
if (bconnected) {
String str = tf.getText().trim();
if (str.length() == 0) {
return;
}
tf.setText("");
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
private class RecvThread implements Runnable {
public void run() {
try {
while (bconnected) {
String str = dis.readUTF();
ta.append(str + "\n");
}
} catch (java.net.SocketException ex) {
bconnected = false;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}