java socket服务器客户端多线程小例子

时间:2022-12-21 22:15:00

java socket服务器客户端多线程小例子——主要参考《疯狂java讲义》

服务器端采用多线程,客户端也采用多线程的方式。在服务器端使用一个ArrayList来保存已经连接的客户端,并且,向客户端返回数据的时候需要遍历这个ArrayList中的每一个客户端socket。当socket断开,或者异常的时候,服务器端能够把这个socket从ArrayList中移除。下面是源码: Server
package com.xueyoucto.xueyou;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
* Hello world!
* Server
*/
class ServerThread implements Runnable{
Socket s = null;
BufferedReader br = null;

public ServerThread(Socket s) throws IOException{
this.s = s;
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
}

@Override
public void run() {
try {
String content = null;
while ((content = readFromClient()) != null){
System.out.println("客户端发来内容:" + content);
for (Socket socket : App.sockets) {
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println(content);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

public String readFromClient(){
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
App.sockets.remove(s);
}
return null;
}
}

public class App {
private static final int SERVER_PORT = 60000;
public static ArrayList<Socket> sockets = new ArrayList<Socket>();
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
while(true){
Socket s = serverSocket.accept();
System.out.println("someone in ...");
sockets.add(s);
new Thread(new ServerThread(s)).start();
}
}
}

Client
package com.xueyoucto.xueyou;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
* Hello world!
* client
*/

class ClientThread implements Runnable{
private Socket s;
BufferedReader br = null;

public ClientThread(Socket s) throws IOException{
this.s = s;
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
}

@Override
public void run() {
String content = null;
try {
while((content = br.readLine()) != null){
System.out.println(content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

public class App {
private static final int SERVER_PORT=60000;
public static void main(String[] args) throws IOException{
System.out.println("Hello World!");
Socket s = new Socket("192.168.1.120",SERVER_PORT);
new Thread(new ClientThread(s)).start();
PrintStream ps = new PrintStream(s.getOutputStream());
String line = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while((line = br.readLine())!=null){
ps.println(line);
}
}
}

运行结果:
先运行server端: java socket服务器客户端多线程小例子
再运行Client: java socket服务器客户端多线程小例子
在client中输入一些内容并且点击回车发送: java socket服务器客户端多线程小例子
此时服务器端有变化 java socket服务器客户端多线程小例子