JAva socketプログラミングの古典的な例


サーバは、各クライアントの情報をリスニングし、受信して各クライアントに送信する
サービス側
package com.java.xiong.Net17;

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

public class RunableSocket implements Runnable {
	//          Socket
	private Socket socket = null;
	//          
	private BufferedReader read = null;

	public RunableSocket(Socket s) throws IOException {
		this.socket = s;
		read = new BufferedReader(
				new InputStreamReader(socket.getInputStream()));
	}

	@Override
	public void run() {
		String line=null;
		try{
			while((line=getClentData())!=null){
				for(Socket s:MyServer.list){
					//          
					PrintStream print=new PrintStream(s.getOutputStream());
					print.println(line);
				}
			}
			
		}catch(IOException  io){
			io.printStackTrace();
		}

	}
	//          
	public String getClentData(){
		String line=null;
		try{
			line=read.readLine();
		}catch(IOException io){
			MyServer.list.remove(socket);
		}
		return line;
	}

}
package com.java.xiong.Net17;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class MyServer {
	
	public static List<Socket> list=new ArrayList<Socket>();
	
	public static void main(String [] args) throws Exception{
		ServerSocket  server=new ServerSocket(30001);
		while(true){
			Socket scoket=server.accept();
			list.add(scoket);
			new Thread(new RunableSocket(scoket)).start();
		}
		
	}

}

クライアント
package com.java.xiong.Net17;

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

//             
public class RubableClient implements Runnable {

	private Socket socket;
	private BufferedReader read;

	public RubableClient(Socket socket) throws IOException {
		this.socket = socket;
		this.read = new BufferedReader(new InputStreamReader(
				this.socket.getInputStream()));
	}

	@Override
	public void run() {
		try{
			String line=null;
			while((line=read.readLine())!=null){
				System.out.print(line);
			}
			
		}catch(IOException  io){
			io.printStackTrace();
		}

	}

}
package com.java.xiong.Net17;

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

public class MyClient {

	public static void main(String[] args) throws Exception, IOException {

		//        
		Socket socket = new Socket("127.0.0.1", 30001);
		new Thread(new RubableClient(socket)).start();
		//     
		PrintStream print = new PrintStream(socket.getOutputStream());
		String line = "";
		BufferedReader read = new BufferedReader(new InputStreamReader(
				System.in));
		while((line=read.readLine())!=null){
			//  Socket      
			print.println(line);
		}
	}

}