服务器群发线程:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//将服务器接收到的信息群发送给其他客户端
public class OneServerMoreClientRunnable {
public static void main(String[] args) {
ExecutorService service=Executors.newFixedThreadPool(3);
ArrayList<Socket>list=null;//list也可以在run()中创建并添加socket看自己那个方便
try {
ServerSocket serverSocket=new ServerSocket(8888);
Socket socket=null;
while(true){
//有一个客户端连接就创建一个线程
socket=serverSocket.accept();
list=new ArrayList<>();
/*
MyThread mThread=new MyThread(socket,list);
//Thread t=new Thread(mThread);
mThread.start();//开启线程
*/service.execute(new MyThread(socket, list));//线程池
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class MyThread extends Thread{
//接收传进来的套接字
private Socket socket;
private ArrayList<Socket> list;
public MyThread(Socket socket,ArrayList<Socket> list) {
this.socket=socket;
this.list=list;
}
InputStream is=null;
OutputStream os=null;
BufferedReader br=null;
String str=null;
String ip=null;
int port;
String str2=null;
@Override
public void run() {
list.add(socket);
try {
is=socket.getInputStream();
br=new BufferedReader(new InputStreamReader(is));
ip=socket.getInetAddress().getHostAddress();
port=socket.getPort();
while(true){
str=br.readLine();
//System.out.println(str);
if(str==null||"".equals(str)||socket==null){
break;
}
str2="ip"+ip+":端口"+port+str;
//遍历发送给其他客户端,第一种
Iterator<Socket>iter=list.iterator();
for(;iter.hasNext();){
socket=iter.next();
os=socket.getOutputStream();
os.write(str2.getBytes());
}
/*//遍历发送给其他客户端,第二种
for(Socket s:list){
os=s.getOutputStream();
os.write(str2.getBytes());
}
*/
}
} catch (IOException e) {
e.printStackTrace();
System.out.println(socket.getInetAddress().getHostAddress()+"退出");
}
try {
is.close();
br.close();
os.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端:
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
/*
* 客户端接收控制台的数据,发送到服务端,
* 当服务端接收到数据后,回客户端一条信息。
*/
public class ClientTcpDemo3 {
public static void main(String[] args) throws Exception {
Socket socket=new Socket("127.0.0.1", 8888);
OutputStream os=socket.getOutputStream();
InputStream is=null;
is=socket.getInputStream();
byte[]b=new byte[1024];
System.out.println("请输入发送数据");
Scanner sc=new Scanner(System.in);
while(true){
String str=sc.nextLine();
if("886".equals(str)){
break;
}
byte[]a=str.getBytes();
//如果接收是用缓冲流的话,有readLine()时,发送端一定要有回车换行符服务器才能接受到
os.write(a, 0, a.length);
os.write("\r\n".getBytes());
int len=is.read(b);
System.out.println(new String (b,0,len));
}
socket.close();
os.close();
}
}
转载于:https://my.oschina.net/u/2541146/blog/596465