多线程应用程序中的问题. [英] Problem in Multi-thread application .

查看:71
本文介绍了多线程应用程序中的问题.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
我创建了一个可以运行的简单命令行多线程应用程序,但是我遇到了一个简单的问题,即当2或3个线程连接到服务器时,服务器需要写入控制台的次数等于连接到我的服务器的客户端的数量,例如2个连接的客户端,我需要例如,写hi,BYE,hi转到客户端1,BYE转到client2.我不喜欢这种方式,因此我需要通过将clientCode用作定义我的客户端并向其发送消息的键来寻求帮助,以下代码将解释clientCode的功能以及更多内容
这是服务器代码:

Hello ,
I created simple command line multithread application it work , but i faced a simple problem which is when 2 or 3 threads connect to server the server need to write to console equals to number of clients connected to my server example 2 clients connected , i need to write for example BYE , hi goes to clients 1 and BYE goes to client2 . i didn''t like this way so i need help by putting clientCode as key to define my client and send the message to it the following code will explain the functionality of clientCode and more things
here is Server code:

package Server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

// TODO: Auto-generated Javadoc
/**
 * The Class Server.
 */
public class Server {

	/** The reader. */
	BufferedReader reader;

	/** The data. */
	String data;

	/** The port. */
	private int port = 7898;

	/** The server socket. */
	private ServerSocket serverSocket;

	/** The socket. */
	private Socket socket;

	/** The input data. */
	String inputData;

	/** The map. */
	HashMap<Integer, Socket> map = new HashMap<Integer, Socket>();

	/** The writer. */
	PrintWriter writer;

	/** The client code. */
	int clientCode = 0;

	/**
	 * Instantiates a new server.
	 * 
	 * @param sa
	 *            the sa
	 */
	public Server(String sa) {

	}

	/**
	 * Instantiates a new server.
	 * @throws InterruptedException 
	 */
	public Server() throws InterruptedException {
		try {
			serverSocket = new ServerSocket(port);
			System.out.println("waiting For connection on this port " + " "
					+ port);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		while (true) {
			try {
				socket = serverSocket.accept();

				Thread thread = new Thread(new ServerManager(socket));
				thread.start();
				thread.sleep(1000L);
			} catch (IOException e) {

				e.printStackTrace();
			}

		}
	}

	/**
	 * The main method.
	 * 
	 * @param args
	 *            the arguments
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 * @throws ClassNotFoundException
	 *             the class not found exception
	 * @throws InterruptedException
	 *             the interrupted exception
	 */
	public static void main(String[] args) throws IOException,
			ClassNotFoundException, InterruptedException {
		Server server = new Server();

		// server.invokingMethod();

	}

}



还有serverManager,其中大部分服务器都放在这里:



and here serverManager which most of server goes here:

package Server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Random;

// TODO: Auto-generated Javadoc
/**
 * The Class ServerManager.
 */
class ServerManager implements Runnable {

	/** The socket. */
	Socket socket = null;

	/** The map. */
	HashMap<Integer, Socket> map = new HashMap<Integer, Socket>();

	/** The input stream. */
	BufferedReader inputStream;

	/** The input. */
	BufferedReader input;

	/** The output stream. */
	BufferedWriter outputStream;

	/** The buffered writer. */
	BufferedWriter bufferedWriter;

	/** The data. */
	String data;

	/** The input data. */
	String inputData;

	/** The client code. */
	int clientCode = 0;

	/**
	 * Instantiates a new server manager.
	 * 
	 * @param clientSocket
	 *            the client socket
	 */
	public ServerManager(Socket clientSocket) {
		this.socket = clientSocket;
		Random random = new Random();
		clientCode = Math.abs(random.nextInt());
	}

	/**
	 * Instantiates a new server manager.
	 */
	public ServerManager() {

	}

	/**
	 * The Class ServerReader.
	 */
	class ServerReader implements Runnable {

		/** The input stream. */
		InputStream inputStream;

		/**
		 * Instantiates a new server reader.
		 * 
		 * @param inputStream
		 *            the input stream
		 */
		public ServerReader(InputStream inputStream) {
			this.inputStream = inputStream;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() {

			// When started keep seeking for socket input data
			while (true) {
				try {
					if (inputStream.available() > 0) {
						byte[] readData = new byte[inputStream.available()];
						System.out.println();
						inputStream.read(readData);
						System.out.println("Data from Client " + clientCode
								+ ": " + new String(readData));

					}
					Thread.sleep(1000L);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	public void run() {

		try {
			System.out.println("The Client with Code " + clientCode + ": "
					+ "Connected");

			Thread thread = new Thread(
					new ServerReader(socket.getInputStream()));

			thread.start();
			outputStream = new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream()));
			add(clientCode);

			data = dataFromConsole().toString();

			send(data);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * Adds the.
	 * 
	 * @param clientCode
	 *            the client code
	 */
	public void add(Integer clientCode) {

		map.put(clientCode, socket);
	}

	/**
	 * Send.
	 * 
	 * @param message
	 *            the message
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 * @throws ClassNotFoundException
	 *             the class not found exception
	 * @throws InterruptedException
	 *             the interrupted exception
	 */
	public void send(String message) throws IOException,
			ClassNotFoundException, InterruptedException {

		outputStream.write(message);
		outputStream.newLine();
		outputStream.flush();

	}

	/**
	 * Data from console.
	 * 
	 * @return the string
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	public String dataFromConsole() throws IOException {
		input = new BufferedReader(new InputStreamReader(System.in));
		inputData = input.readLine();
		return inputData;
	}

	public void Disconnect() throws IOException {
		while (true) {

			input.close();
			outputStream.close();
			socket.close();
		}

	}
}


我的客户端代码以相同的方式构建,这里期望有多线程部分.


My client code built at the same way here expect the multithreading part.

推荐答案

您需要对代码进行一些拆分,我的建议是:

ServerApp
创建并启动用于管理所有连接的Server.

服务器
在它自己的线程上运行,并包含一个接受入站连接的Listener和所有连接的Session集合.

Listener
在它自己的线程中运行,创建一个ServerSocket,并为分配给Server的每个Socket创建一个Session.

会话
再次在它自己的线程上运行.
从客户端获取入站消息,并将其转发到Server.
接受来自Server的出站消息并将其转发给客户端.

三个服务器端组件中的每个组件都必须是线程安全的,并且可以在两个位置调用同步方法.
我将通过在所有会话的Server中具有集合来管理一切,然后Session本身将保留消息以进行处理,并在有消息时通知服务器.

如果您想要更多的想法,请尝试搜索多线程聊天服务器",因为那样可能会为您提供很多您需要涵盖的概念,而又不会太复杂.
You need to split up your code a bit, my suggestion would be:

ServerApp
Creates and starts a Server that manages all the connections.

Server
Runs on it''s own thread and contains a single Listener that accepts inbound connections and a collection of Sessions for all of the connections.

Listener
Runs in it''s own thread, creates a ServerSocket and creates a Session for each Socket that is given to the Server.

Session
Again runs on it''s own thread.
Takes inbound messages from the client and forwards them to the Server.
Accepts outbound messages from the Server and forwards them to the client.

Each of the three server side components need to be thread safe, synchronize methods that can be called from two places.
I would manage everything by having a collection in the Server of all the sessions and then the Sessions themselves will keep the messages for processing and notify the server when they have something.

If you want more ideas, try searching for "multi threaded chat server" as that would probably give you a lot of the concepts you need to cover without being too complicated.


这篇关于多线程应用程序中的问题.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆