Java socket编程的一些问题 我想要实现一个一个服务器端和多个客户端进行连接,服务器端不断接受所有客户端发送的数据。而服务器端会同时向所有客户端发送同样的数据。这个该怎么实现? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 今天略无聊,给你贴个代码吧import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import java.net.SocketTimeoutException;import java.util.ArrayList;import java.util.HashSet;import java.util.List;public class Server extends Thread { public static void main(String[] args) { TServer server = new TServer(); server.start(); server.sendData(new byte[]{1, 1, 0});//应该等有客户端连接上以后,再调用此方法。 }}/** * 服务端程序 * @author Administrator * */class TServer extends Thread { ServerSocket se; static int clientNum = 0; String user[] = new String[20]; public TServer() { try { se = new ServerSocket(5432); } catch (IOException e) { e.printStackTrace(); } this.start(); } public void run() { try { while (true) { //接受新的客户端连接 Socket socket = se.accept(); //开启与客户端的单独会话线程 ClientSession session = new ClientSession(socket); session.start(); //统一存放客户端会话 ClientSessionManager.save(session); } } catch (IOException e) { e.printStackTrace(); } } /** * 向所有客户端发送同样的数据 */ public void sendData(byte[] data){ List<ClientSession> sessions = ClientSessionManager.getAllSessions(); for(ClientSession session : sessions){ try{ if(session.isConnected()){ Socket socket = session.getSocket(); socket.getOutputStream().write(data); } }catch(Exception e){ e.printStackTrace(); } } }}/** * 客户端会话管理 * @author Administrator * */class ClientSessionManager{ private static HashSet<ClientSession> sessions = new HashSet<ClientSession>(); /** * 增加客户端会话 * @param session */ public static synchronized void save(ClientSession session){ sessions.add(session); } /** * 移除客户端会话 * @param session */ public static synchronized void close(ClientSession session){ sessions.remove(session); if(session != null){ try { session.getSocket().close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 检测连接性。将断开连接的会话移除。 */ public static synchronized void check(){ ArrayList<ClientSession> removes = new ArrayList<ClientSession>(); for(ClientSession session : sessions){ if(!session.isConnected()){ removes.add(session); session.close(); } } sessions.removeAll(removes); } public static synchronized List<ClientSession> getAllSessions(){ ArrayList<ClientSession> list = new ArrayList<ClientSession>(sessions.size()); list.addAll(sessions); return list; }}/** * 处理单个客户端的会话 * @author Administrator * */class ClientSession extends Thread{ /** * 服务器与单个客户端之前的会话 */ private Socket socket; private boolean work = true; public ClientSession(Socket socket){ this.socket = socket; } @Override public void run() { while(work){ try { //服务端单独接收每个客户端的数据 this.socket.setSoTimeout(1000); int data = this.socket.getInputStream().read(); if(data == -1){ //客户端主动(正常)断开连接 break; } System.out.println("收到客户端发送的数据:" + data); }catch (SocketTimeoutException e){ //1秒内还没数据 e.printStackTrace(); } catch (IOException e) { //异常断开连接 break; } } this.close(); } public boolean isConnected(){ return this.socket.isConnected(); } public Socket getSocket() { return socket; } //关闭连接 public void close(){ this.work = false; try { this.socket.shutdownOutput(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { this.socket.shutdownInput(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 新手求助!Eclipse中连接sqlserver2000数据库,用maven管理包,出现如下错误 Random方法到底是什么原理和MATH有什么不一样 几个小问题 Java中的类和对象究竟放在了哪里 redirect和forword 『请教』java方法调用C函数时的参数传递问题 如何实现使用java读取控制台的输入数据? 请问怎样让jTable中的column不与其他的column交换位置?谢谢了! 哪里有java的API文档下载? 使用连接池时连接数据库的错误,快来帮帮忙! Win 10环境下,F10和F11快捷键都没法用。。 Linux下可以用 JNI或 JNA调用 dll吗?
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Server extends Thread {
public static void main(String[] args) {
TServer server = new TServer();
server.start();
server.sendData(new byte[]{1, 1, 0});//应该等有客户端连接上以后,再调用此方法。
}
}/**
* 服务端程序
* @author Administrator
*
*/
class TServer extends Thread {
ServerSocket se;
static int clientNum = 0;
String user[] = new String[20]; public TServer() {
try {
se = new ServerSocket(5432);
} catch (IOException e) {
e.printStackTrace();
}
this.start();
} public void run() {
try {
while (true) {
//接受新的客户端连接
Socket socket = se.accept();
//开启与客户端的单独会话线程
ClientSession session = new ClientSession(socket);
session.start();
//统一存放客户端会话
ClientSessionManager.save(session);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 向所有客户端发送同样的数据
*/
public void sendData(byte[] data){
List<ClientSession> sessions = ClientSessionManager.getAllSessions();
for(ClientSession session : sessions){
try{
if(session.isConnected()){
Socket socket = session.getSocket();
socket.getOutputStream().write(data);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}/**
* 客户端会话管理
* @author Administrator
*
*/
class ClientSessionManager{
private static HashSet<ClientSession> sessions = new HashSet<ClientSession>();
/**
* 增加客户端会话
* @param session
*/
public static synchronized void save(ClientSession session){
sessions.add(session);
}
/**
* 移除客户端会话
* @param session
*/
public static synchronized void close(ClientSession session){
sessions.remove(session);
if(session != null){
try {
session.getSocket().close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 检测连接性。将断开连接的会话移除。
*/
public static synchronized void check(){
ArrayList<ClientSession> removes = new ArrayList<ClientSession>();
for(ClientSession session : sessions){
if(!session.isConnected()){
removes.add(session);
session.close();
}
}
sessions.removeAll(removes);
}
public static synchronized List<ClientSession> getAllSessions(){
ArrayList<ClientSession> list = new ArrayList<ClientSession>(sessions.size());
list.addAll(sessions);
return list;
}
}/**
* 处理单个客户端的会话
* @author Administrator
*
*/
class ClientSession extends Thread{
/**
* 服务器与单个客户端之前的会话
*/
private Socket socket;
private boolean work = true;
public ClientSession(Socket socket){
this.socket = socket;
}
@Override
public void run() {
while(work){
try {
//服务端单独接收每个客户端的数据
this.socket.setSoTimeout(1000);
int data = this.socket.getInputStream().read();
if(data == -1){
//客户端主动(正常)断开连接
break;
}
System.out.println("收到客户端发送的数据:" + data);
}catch (SocketTimeoutException e){
//1秒内还没数据
e.printStackTrace();
} catch (IOException e) {
//异常断开连接
break;
}
}
this.close();
} public boolean isConnected(){
return this.socket.isConnected();
}
public Socket getSocket() {
return socket;
}
//关闭连接
public void close(){
this.work = false;
try {
this.socket.shutdownOutput();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
this.socket.shutdownInput();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}