Java 在唯一服务器中执行两个可运行对象。插座
我有一个我认为很容易解决的问题,但我不知道如何解决 如果我的客户机使用参数Java 在唯一服务器中执行两个可运行对象。插座,java,multithreading,sockets,runnable,Java,Multithreading,Sockets,Runnable,我有一个我认为很容易解决的问题,但我不知道如何解决 如果我的客户机使用参数-p执行,服务器将从数据库创建一个文件并将其返回给客户机。如果客户机没有参数,那么它将向服务器发送一个可序列化对象,服务器将其保存在数据库中 我的客户代码: public class cliente { public static void main(String[] args) { // común String hostname = "localhost"; i
-p
执行,服务器将从数据库创建一个文件并将其返回给客户机。如果客户机没有参数,那么它将向服务器发送一个可序列化对象,服务器将其保存在数据库中
我的客户代码:
public class cliente {
public static void main(String[] args) {
// común
String hostname = "localhost";
int port = 6789;
Socket clientSocket = null;
// descarga fichero
String ficheroDescargado = null;
// Almacena datos
BufferedReader br = null;
ObjectOutputStream os = null;
String str = "";
Map<DatosAEnviar, DatosAEnviar> datos = new TreeMap<DatosAEnviar, DatosAEnviar>();
if (args.length != 0 && args[0] == "-p") {
System.out.println("Descarga fichero");
try {
// Instanciamos la conexión con el socket
clientSocket = new Socket(hostname, port);
System.out.println("IP " + clientSocket.getInetAddress().toString());
ficheroDescargado = "descarga_tienda_"
+ clientSocket.getInetAddress().toString()
.replace("localhost/", "") + ".txt";
byte[] mybytearray = new byte[1024];
InputStream is = clientSocket.getInputStream();
FileOutputStream fos = new FileOutputStream(ficheroDescargado);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
// Cerramos el socket
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
} catch (IOException e) {
System.err.println("Por favor, inicialice primero el servidor "
+ hostname);
}
} else {
System.out.println("Leer fichero");
datos = leerFichero();
System.out.println("Pintamos lo recibido");
for (Entry<DatosAEnviar, DatosAEnviar> itrDatos : datos.entrySet()) {
DatosAEnviar clave = itrDatos.getKey();
DatosAEnviar valor = itrDatos.getValue();
System.out.println(clave + " -> " + valor.toString());
}
try {
// Instanciamos la conexión con el socket
clientSocket = new Socket(hostname, port);
// Abrimos el canal entrada de datos. Nos la enviará el servidor
// para confirmar que ha procesado OK
br = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
// Abrimos el canal de salida para mandar al servidor la
// colección
// MapTree
os = new ObjectOutputStream(clientSocket.getOutputStream());
// Enviamos por el canal de salida hacia el servidor los daros
// en el
// MapTree
os.writeObject(datos);
// Esperamos la respuesta del servidor.
while ((str = (String) br.readLine()) != null) {
System.out.println(str);
if (str.equals("bye"))
break;
}
// Cerramos el canal de salida
os.close();
// Cerramos el canal de entrada
br.close();
// Cerramos el socket
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
} catch (IOException e) {
System.err.println("Por favor, inicialice primero el servidor"
+ hostname);
}
}
}
公共类客户{
公共静态void main(字符串[]args){
//科姆
字符串hostname=“localhost”;
int端口=6789;
套接字clientSocket=null;
//德斯卡加菲切罗
字符串ficheroDescargado=null;
//达托斯阿尔马塞纳酒店
BufferedReader br=null;
ObjectOutputStream os=null;
字符串str=“”;
Map datos=new TreeMap();
如果(args.length!=0&&args[0]=“-p”){
System.out.println(“Descarga fichero”);
试一试{
//conexión Conel插座实例
clientSocket=新套接字(主机名、端口);
System.out.println(“IP”+clientSocket.getInetAddress().toString());
ficheroDescargado=“描述”
+clientSocket.getInetAddress().toString()
.replace(“localhost/,”)+“.txt”;
字节[]mybytearray=新字节[1024];
InputStream=clientSocket.getInputStream();
FileOutputStream fos=新的FileOutputStream(ficheroDescargado);
BufferedOutputStream bos=新的BufferedOutputStream(fos);
int bytesRead=is.read(mybytearray,0,mybytearray.length);
写入(mybytearray,0,bytesRead);
bos.close();
//Cerramos el插座
clientSocket.close();
}捕获(未知后异常e){
System.err.println(“不知道主机:“+hostname”);
}捕获(IOE异常){
System.err.println(“赞成,特别是primero el servidor”
+主机名);
}
}否则{
System.out.println(“Leer fichero”);
datos=leerFichero();
System.out.println(“Pintamos lo recibido”);
对于(条目itrDatos:datos.entrySet()){
DatosAEnviar clave=itrDatos.getKey();
DATOSAEVIAR valor=itrDatos.getValue();
System.out.println(clave+“->”+valor.toString());
}
试一试{
//conexión Conel插座实例
clientSocket=新套接字(主机名、端口);
//Abrimos el canal entrada de datos.Nos la enviaráel servidor
//确认程序是否正常
br=新的BufferedReader(新的InputStreamReader(
getInputStream());
//Abrimos el canal de salida para mandar al-servidor la
//科尔奇翁
//地图树
os=newObjectOutputStream(clientSocket.getOutputStream());
//塞维多洛斯达罗斯运河环境
//恩埃尔
//地图树
os.writeObject(datos);
//埃斯佩拉莫斯·勒斯维多尔酒店。
而((str=(String)br.readLine())!=null){
系统输出打印项次(str);
如果(str.equals(“bye”))
打破
}
//塞拉莫斯萨利达运河酒店
os.close();
//塞拉莫斯恩特拉达运河酒店
br.close();
//Cerramos el插座
clientSocket.close();
}捕获(未知后异常e){
System.err.println(“不知道主机:“+hostname”);
}捕获(IOE异常){
System.err.println(“赞成,特别是primero el servidor”
+主机名);
}
}
}
客户端正常,工作正常。问题出在服务器上:
我的服务器代码:
public class Server2 {
public static void main(String args[]) {
int port = 6789;
Server2 server = new Server2(port);
server.startServer();
}
// Definimos el socket del servidor y el socket del cliente
ServerSocket echoServer = null;
Socket clientSocket = null;
// Definimos la variable para almacenar el nº de conexiones
int numConnections = 0;
int port;
public Server2(int port) {
this.port = port;
}
public void stopServer() {
System.out.println("Server cleaning up.");
System.exit(0);
}
public void startServer() {
// Abrimos el socket del servidor. No se pueden definir puertos por
// debajo de 1024
try {
echoServer = new ServerSocket(port);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Servidor listo y esperando conexiones de clientes...");
while (true) {
try {
clientSocket = echoServer.accept();
numConnections++;
**// Insert in BD
Server2Connection oneconnection = new Server2Connection(clientSocket, numConnections, this);
// Generate file and send to client
//Server1Connection oneconnection = new Server1Connection(clientSocket, numConnections, this);
new Thread(oneconnection).start();**
} catch (IOException e) {
System.out.println(e);
}
}
}
}
class Server2Connection implements Runnable {
PrintStream os;
Socket clientSocket;
int id;
Server2 server;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
Map<DatosAEnviar, DatosAEnviar> datos;
public Server2Connection(Socket clientSocket, int id, Server2 server) {
this.clientSocket = clientSocket;
this.id = id;
this.server = server;
System.out.println("Conexión " + id + " establecida en: " + clientSocket);
System.out.println("Conexión " + id + " establecida por: "
+ clientSocket.getInetAddress());
try {
os = new PrintStream(clientSocket.getOutputStream());
ois = new ObjectInputStream(clientSocket.getInputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
Connection con;
Statement smt;
boolean serverStop = false;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel",
"root", "root");
// Hacemos el cast del stream recibido al tipo de objeto esperado,
// en este caso un objeto del tipo MapTree
while ((datos = (Map<DatosAEnviar, DatosAEnviar>) ois.readObject()) != null) {
for (Entry<DatosAEnviar, DatosAEnviar> itrDatos : datos.entrySet()) {
DatosAEnviar clave = itrDatos.getKey();
DatosAEnviar valor = itrDatos.getValue();
System.out.println(clave + " -> " + valor.toString());
// Insertamos en la tabla de BBDD cada registro del MapTree
// recibido
String query = "insert into registro (id_conex, vendedor, ventas, ip_tienda) values( '"
+ id
+ "','"
+ valor.getNombre()
+ "','"
+ valor.getVentas()
+ "','"
+ clientSocket.getInetAddress().toString().replace("/", "") + "');";
smt = con.createStatement();
smt.executeUpdate(query);
}
// Enviamos al cliente confirmación de que hemos procesado la
// información correctamente
os.println("bye");
break;
}
System.out.println("Conexión " + id + " cerrada.");
// Cerramos la conexión de BBDD
con.close();
// Cerramos el canal de entrada
ois.close();
// Cerramos el canal de salida
os.close();
// Cerramos el socket con el cliente
clientSocket.close();
if (serverStop)
server.stopServer();
} catch (IOException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Server1Connection implements Runnable {
Socket clientSocket;
int id;
Server2 server;
File myFile = null;
OutputStream os = null;
BufferedInputStream bis = null;
FileInputStream fis = null;
public Server1Connection(Socket clientSocket, int id, Server2 server) {
this.clientSocket = clientSocket;
this.id = id;
this.server = server;
System.out.println("Conexión " + id + " establecida en: " + clientSocket);
try {
os = clientSocket.getOutputStream();
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
boolean serverStop = false;
Connection con;
Statement smt;
ResultSet rs;
try {
// Conexión a la BBDD
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel","root", "root");
//Generamos el fichero
FileWriter writer = new FileWriter("registro_tieda_"+clientSocket.getInetAddress().toString().replace("/", "") + ".txt");
smt=con.createStatement();
String query ="SELECT * FROM registro WHERE ip_tienda='" + clientSocket.getInetAddress().toString().replace("/", "") + "';";
rs = smt.executeQuery(query);
while(rs.next()) {
writer.append(rs.getString(3));
writer.append(';');
writer.append(rs.getString(4));
writer.append(';');
writer.append(rs.getString(5));
writer.append('\n');
}
writer.close();
// Enviamos el fichero
File myFile = new File("registro_tieda_"+clientSocket.getInetAddress().toString().replace("/", "") + ".txt");
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
byte[] mybytearray = new byte[(int) myFile.length()];
bis.read(mybytearray, 0, mybytearray.length);
os.write(mybytearray, 0, mybytearray.length);
os.flush();
bis.close();
// Enviamos al cliente confirmación de que hemos procesado la
// información correctamente
System.out.println("Conexión " + id + " cerrada.");
// Cerramos la conexión de BBDD
con.close();
clientSocket.close();
// Cerramos el fichero
if (serverStop)
server.stopServer();
} catch (IOException e) {
System.out.println(e);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
公共类服务器2{
公共静态void main(字符串参数[]){
int端口=6789;
Server2服务器=新的Server2(端口);
server.startServer();
}
//定义服务插座和客户插座
ServerSocket echoServer=null;
套接字clientSocket=null;
//定义可变的气候变化
int numConnections=0;
国际港口;
公用服务器2(int端口){
this.port=端口;
}
公共void stopServer(){
System.out.println(“服务器清理”);
系统出口(0);
}
public void startServer(){
//Abrimos el socket del servidor.没有明确的定义
//德巴乔1024
试一试{
echoServer=新服务器套接字(端口);
}捕获(IOE异常){
系统输出打印ln(e);
}
System.out.println(“Servidor listo y esperando conexiones de clientes…”);
while(true){
试一试{
clientSocket=echoServer.accept();
numConnections++;
**//在BD中插入
Server2Connection oneconnection=新的Server2Connection(clientSocket、numConnections、this);
//生成文件并发送到客户端
//server1connectiononeconnection=newserver1connection(clientSocket、numConnections、this);
新线程(oneconnection.start()**
}捕获(IOE异常){
系统输出打印ln(e);
}
}
}
}
类Server2Connection实现可运行{
打印流操作系统;
插座客户端插座;
int-id;
服务器2服务器;
ObjectOutputStream oos=null;
ObjectInputStream ois=null;
地图datos;
公共服务器2CO