socket通信之客户端数据互发(通过服务器转发)

服务器端

package chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
//服务器可以接受多个客户端连接
//等待客户端连接   已连接上的socket,等待客户端发送数据
public class ServerSocketDemo6 {
	public static final List<Client> CLIENTS = new ArrayList<Client>();
	public ServerSocketDemo6() {
		//局部变量没有默认值,必须先初始化,再使用
		// TODO Auto-generated method stub
		ServerSocket serverSocket = null;
		Socket socket = null;
		try {
			serverSocket = new ServerSocket(8080);
			System.out.println("服务器8080端口正常开启");
		} catch (Exception e) {
			// e.printStackTrace();
			throw new RuntimeException("服务器端口被占用");
		}

		System.out.println("服务器等待客户端连接");
		try {
			while(true){
				socket = serverSocket.accept();
				System.out.println("有客户端连接成功");
				System.out.println(socket.getLocalAddress()+"    "+socket.getLocalPort()+"  "+
				socket.getInetAddress()+"  "+socket.getPort());
				Client client = new Client(socket);
				CLIENTS.add(client);
				System.out.println(CLIENTS);
				client.start();
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new ServerSocketDemo6();

	}

}

实现服务器转发的线程类

package chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;

public class Client extends Thread {
	private String ip;
	private Socket socket;
	private BufferedReader reader;
	private PrintWriter out;
	
	@Override
	public String toString() {
		return "Client [ip=" + ip + "]";
	}

	public String getIP() {
		return ip;
	}

	public PrintWriter getOut() {
		return out;
	}

	public Client(Socket socket) {
		this.socket = socket;
		ip = socket.getInetAddress().getHostAddress();
		System.out.println(ip);
		try {
			reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream(),"UTF-8"));

			out = new PrintWriter(socket.getOutputStream(), true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	// 运行在服务器端,接受客户端发过来的信息,
	@Override
	public void run() {
		super.run();
		try {
			String str = null;
			// 服务器端,循环接受数据
			while ((str = reader.readLine()) != null) {
				
				String[] strs = str.split(":");
				//socket.getInetAddress().getHostAddress()  谁发的信息
				//strs[0]  接受信息目标
				//strs[1]  信息内容
				System.out.println("接受到来自  "+socket.getInetAddress().getHostAddress()+"  "+strs[1]);
				String ip = strs[0];
				if (str.equals("exit"))
					break;
				else if ("all".equalsIgnoreCase("ip")) {
					for (Client client : ServerSocketDemo6.CLIENTS) {
						client.getOut().println(strs[1]);
					}
				} else {
					for (Client client : ServerSocketDemo6.CLIENTS) {
						if (client.getIP().equals(ip)) {
							client.getOut().println(strs[1]);
							break;
						}
					}
				}

				
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null)
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if (socket != null)
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}

	}
}

发送消息的客户端

package lessons18;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import javax.swing.JOptionPane;

public class ClientSocketDemo6 {

	public ClientSocketDemo6() {
		Socket socket = null;
		
		
		try {
		//此处应写目标客户端的ip
			socket = new Socket("127.0.0.1", 8080);
			System.out.println(socket.getLocalAddress()+"    "+socket.getLocalPort()+"  "+
					socket.getInetAddress()+"  "+socket.getPort());
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "请检查ip和端口是否正确,无法连接服务器");
			throw new RuntimeException("请检查ip和端口是否正确,无法连接服务器");
		}
		System.out.println("您好,如果退出,输入exit,如果发送信息,请输入ip:message");
		new SendInfoThread(socket).start();
		new GetInfoThread(socket).start();
		
		
		
	}
	class GetInfoThread extends Thread{
		private Socket socket;
		private BufferedReader reader;
		public GetInfoThread(Socket socket){
			this.socket = socket;
			try {
				reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException("请检查ip和端口是否正确,无法连接服务器");
			}
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			String str = null;
			try {
				while ((str = reader.readLine()) != null){
					System.out.println("收到来自服务器     "+socket.getInetAddress().getHostAddress()+"  "+str);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	class SendInfoThread extends Thread{
		private Scanner scanner = new Scanner(System.in);
		private PrintWriter out;
		private Socket socket;
		public SendInfoThread(Socket socket){
			this.socket = socket;
			try {
				out = new PrintWriter(socket.getOutputStream(), true);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException("请检查ip和端口是否正确,无法连接服务器");
			}
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			
			try {
				String str = null;
				while(true){
					str = scanner.nextLine();
					out.println(str);
					if(str.equals("exit"))
						break;
				}
			} catch (Exception e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(null, "服务器出异常,请联系管理员");
			} finally{
				if(out != null)
					out.close();
				if(socket != null)
					try {
						socket.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
			
		}
	}
	

	public static void main(String[] args) {
		new ClientSocketDemo6();
	}

}

你可能感兴趣的:(socket)