could not disconnect socket - java

Here is my tcpClient class:
import java.io.*;
import java.net.*;
public class tcpClient
{
private String _ip;
private int _port;
private Socket _clientSocket;
public tcpClient(String IP, int Port)
{
_ip = IP;
_port = Port;
}
public boolean createSocket()
{
boolean retSt = false;
try
{
_clientSocket = new Socket(this._ip, this._port);
retSt = true;
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return retSt;
}
public boolean disposeSocket()
{
boolean retSt = false;
try
{
_clientSocket.shutdownInput();
_clientSocket.shutdownOutput();
_clientSocket.close();
retSt = true;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return retSt;
}
public boolean isConnected()
{
return _clientSocket.isConnected();
}
}
Here is my main method:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
public class cos
{
public static void main(String[] args)
{
tcpClient client = new tcpClient("192.168.10.39", 1234);
client.createSocket();
System.out.println(client.isConnected());
client.disposeSocket();
System.out.println(client.isConnected());
client.createSocket();
System.out.println(client.isConnected());
client.disposeSocket();
System.out.println(client.isConnected());
}
}
Here is my console output:
true
true
true
true
Why couldn't i disconnect from server?

from java doc:
Note: Closing a socket doesn't clear its connection state, which means
this method will return true for a closed socket (see isClosed()) if
it was successfuly connected prior to being closed.

Related

Limit number of clients that will connect through the server

I need to limit the number of client that can connect to the server . I only want 3 clients that can connect not more.
I tried if else conditions. and some loops.
public class server {
ServerSocket ss;
boolean quite=false;
ArrayList<MultiServerConnection> OurDomainsConnections=new ArrayList<MultiServerConnection>();
public static void main(String[] args) {
new server();
}
public server() {
try {
//TODO use method to take this as an input from user)
ss=new ServerSocket(3333);//here we are using connection 3333 (change as you want
while(!quite)
{
Socket s=ss.accept();//when a connection to the domain is found we accept it
MultiServerConnection OurConnection = new MultiServerConnection(s,this);
OurConnection.start();//Start Thread
OurDomainsConnections.add(OurConnection);//add connection to our Domain Connection
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//make sure its bloody same with client it took my 15 min to realize that XD
}
}
public class MultiServerConnection extends Thread {
Socket s;
DataInputStream din;
DataOutputStream dout;
server ss;
boolean quite=false;
public MultiServerConnection(Socket OurSocket,server OurServer)
{
super("MultiServerConnection");//server connection thread
this.s=OurSocket;
this.ss=OurServer;
}
public void ServerOutClientIn(String OutText)
{
try {
long ThreadID=this.getId();
dout.writeUTF(OutText);
dout.flush();//this is because of a buffer error :<
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void ServerOutAllClientIn(String OutText)
{
for(int i=0;i<ss.OurDomainsConnections.size();i++)
{
MultiServerConnection Connection=ss.OurDomainsConnections.get(i);
Connection.ServerOutClientIn(OutText);
}
}
public void run()
{
try {
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
while(!quite)
{
while(din.available()==0)
{
try {
Thread.sleep(1);//sleep if there is not data coming
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String ComingText=din.readUTF();
ServerOutAllClientIn(ComingText);
}
din.close();
dout.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class MultiClients extends Thread {
Socket s;
DataInputStream din;
DataOutputStream dout;
boolean quite=false;
public ClientData c;
public interface1 GUI;
public MultiClients(Socket OurMultiSocket, interface1 gui)
{
s=OurMultiSocket;
c=new ClientData();
GUI=gui;
}
public void ClientOutServerIn(String Text)
{
//write the line from console to server
try {
if(Text.equals("change channel"))
{
System.out.print("sending changing channel: "+Text+"\n");
dout.writeUTF(Text);
dout.flush();
}
else if(Text.equals("new user"))
{
System.out.print("sending new user: "+ Text+"\n");
dout.writeUTF(Text+":"+c.GetName()+"="+c.GetChannel());
dout.flush();
}
else
{
dout.writeUTF(c.GetChannel()+"="+this.getName()+": "+Text);
dout.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void SetClient(String channel,String Name)
{
c.SetName(Name);
c.SetChannel(channel);
}
public void run()
{
try {
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
while(!quite)
{
try {
while(din.available()==0)
{
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//if there is something just show it on console
//and then go back and do the same
String reply=din.readUTF();
String Chan=ExtractChannel(reply);
String name=ExtractName(reply);
/*if (reply.equals("change channel"))
{
System.out.print("changing channel in body: "+reply+"\n");
//GUI.ClearDisplay();
setChangedChannel();
}*/
if(name.equals("new user"))
{
System.out.print("new user in body: "+reply+"\n");
//GUI.ClearDisplay();
setChannel(reply);
}
else
{
PrintReply(Chan,reply);
}
//System.out.println(reply);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
din.close();
dout.close();
s.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
din.close();
dout.close();
s.close();
} catch (IOException x) {
// TODO Auto-generated catch block
x.printStackTrace();
}
}
}
public void CloseClient()
{
try {
din.close();
dout.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String ExtractName(String x)
{
String[]Y=x.split(":");
return Y[0];
}
public String ExtractChannel(String X)
{
String[]Y=X.split("=");
return Y[0];
}
public void PrintReply(String Chan,String Rep)
{
if(c.GetChannel().equals(Chan))
{
String []Y=Rep.split("=");
GUI.setDisplay(Y[1]);
//System.out.println(Y[1]+"\n \n \n \n");
}
}
public void setChannel(String x)
{
String []Y=x.split(":");
String []Z=Y[1].split("=");
System.out.print("setting "+Z[0]+" channel to "+Z[1]+"\n");
GUI.setUserInChannel(Z[0]);
}
public void setChangedChannel()
{
GUI.setUserInChannel(c.GetName()+": "+c.GetChannel());
}
class ClientData
{
public String ClientName;
public String channel;
public void SetChannel(String Chan)
{
channel=Chan;
}
public void SetName(String name)
{
ClientName=name;
}
public String GetChannel()
{
return channel;
}
public String GetName()
{
return ClientName;
}
}
}
in this code. more than 5 user can can chat together. i only want to allow 3 user to connect and to chat.
You can use AtomicInteger as a counter to check how many clients you have already connected:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
public class server {
ServerSocket ss;
boolean quite=false;
ArrayList<MultiServerConnection> OurDomainsConnections=new ArrayList<MultiServerConnection>();
final AtomicInteger runningCount = new AtomicInteger(0);
final Integer limit = 3;
public static void main(String[] args) {
new server();
}
public server() {
try {
//TODO use method to take this as an input from user)
ss=new ServerSocket(3333);//here we are using connection 3333 (change as you want
while(!quite)
{
Socket s=ss.accept();//when a connection to the domain is found we accept it
if (runningCount.incrementAndGet() < limit){ //increment number of clients and check
MultiServerConnection OurConnection = new MultiServerConnection(s,this, runningCount::decrementAndGet);
OurConnection.start();//Start Thread
OurDomainsConnections.add(OurConnection);//add connection to our Domain Connection
} else {
runningCount.decrementAndGet();
s.close();
System.out.println("limit exceeded");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//make sure its bloody same with client it took my 15 min to realize that XD
}
}
interface Callback {
void call();
}
class MultiServerConnection extends Thread {
Socket s;
DataInputStream din;
DataOutputStream dout;
server ss;
boolean quite=false;
final Callback callbackOnFinish;
public MultiServerConnection(Socket OurSocket,server OurServer, Callback callbackOnFinish)
{
super("MultiServerConnection");//server connection thread
this.s=OurSocket;
this.ss=OurServer;
this.callbackOnFinish = callbackOnFinish;
}
public void ServerOutClientIn(String OutText)
{
try {
long ThreadID=this.getId();
dout.writeUTF(OutText);
dout.flush();//this is because of a buffer error :<
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void ServerOutAllClientIn(String OutText)
{
for(int i=0;i<ss.OurDomainsConnections.size();i++)
{
MultiServerConnection Connection=ss.OurDomainsConnections.get(i);
Connection.ServerOutClientIn(OutText);
}
}
public void run()
{
try {
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
while(!quite)
{
while(din.available()==0)
{
try {
Thread.sleep(1);//sleep if there is not data coming
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String ComingText=din.readUTF();
ServerOutAllClientIn(ComingText);
}
din.close();
dout.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
callbackOnFinish.call();
}
}
}
When a new connection is accepted runningCount is atomically increased and value is got by runningCount.incrementAndGet(). Then if value below the limit - new MultiServerConnection is created with a callback. The callback is used for decrementing a counter on exit. If counter equal or above the limit => socket will be closed and error message printed. It is good to have a message passed to the socket.
P.S. I have not reviewed your solution. I've just added the feture you requested.

I can't connect more than one sensor to the server in my java socket program

I Have implemented a server and client using sockets. In that multiple clients must able to connected.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Set;
import sensors.FireAlarmSensor;
public class SensorServer {
private static final int port = 9000;
private static HashMap<String, PrintWriter> fireSensorPrintersList = new HashMap<String, PrintWriter>();
private static HashMap<String,FireAlarmSensor> fireSensorsList = new HashMap<String,FireAlarmSensor>();
private static String sensorIDNumber;
private static double temperatureLevel;
private static double CO2Level;
private static double batteryLevel;
private static double smokeLevel;
public static void main(String args[]){
System.out.println("Sensor Server Is Running");
ServerSocket clientListener = null;
try {
clientListener = new ServerSocket(port);
new sensorHandler(clientListener.accept()).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
clientListener.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static class sensorHandler extends Thread{
private String sensorID;
private Socket socket;
private BufferedReader receiver;
private PrintWriter sender;
public sensorHandler(Socket socket) {
this.socket = socket;
try {
this.receiver = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.sender = new PrintWriter(socket.getOutputStream(),true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run(){
while(true){
sender.println("REQUESTID");
try {
sensorID = receiver.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(sensorID == null){
System.out.println("Empty Sensor ID");
}
synchronized (fireSensorPrintersList) {
if(!fireSensorPrintersList.containsKey(sensorID)){
fireSensorPrintersList.put(sensorID,sender);
break;
}
}
}
sender.println("SENSORACCEPTED");
try{
while(true){
//Set<String> sensorIDList= fireSensorPrintersList.keySet();
/*for(PrintWriter writer:fireSensorPrintersList.values()){
sensorIDNumber = fireSensorsList.get(sensorIDList).getSensorID();
temperatureLevel = fireSensorsList.get(sensorIDList).getTemperatureLevel();
batteryLevel = fireSensorsList.get(sensorIDList).getBatteryLevel();
CO2Level = fireSensorsList.get(sensorIDList).getCO2Level();
smokeLevel = fireSensorsList.get(sensorIDList).getSmokeLevel();
}*/
/*try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
finally {
try {
socket.close();
System.out.println("Sensor server closed");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Here is the code of client(Sensor).
package sensors;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.Socket;
import java.util.Scanner;
public class FireAlarmSensor implements Serializable{
BufferedReader lineIn;
PrintWriter lineOut;
private String sensorID = "Not Set";
private BatterySensor batterySensor;
private TemperatureSensor temperatureSensor;
private SmokeSensor smokeSensor;
private CO2Sensor co2Sensor;
public FireAlarmSensor(String sensorID){
this.sensorID = sensorID;
this.batterySensor = new BatterySensor();
this.temperatureSensor = new TemperatureSensor();
this.smokeSensor = new SmokeSensor();
this.co2Sensor = new CO2Sensor();
}
public FireAlarmSensor(){
/*JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);*/
}
public String getSensorID(){
return this.sensorID;
}
public double getBatteryLevel(){
return batterySensor.getSensorData();
}
public double getTemperatureLevel(){
return temperatureSensor.getSensorData();
}
public double getSmokeLevel(){
return smokeSensor.getSensorData();
}
public double getCO2Level(){
return co2Sensor.getSensorData();
}
public void run(){
String serverAddress = "localhost";
Socket socket = null;
try {
socket = new Socket(serverAddress,9000);
lineIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
lineOut = new PrintWriter(socket.getOutputStream(),true);
while(true){
String serverInput = lineIn.readLine();
if(serverInput.startsWith("REQUESTID")){
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the Sensor ID : ");
String sensorID = userInput.nextLine();
lineOut.println(sensorID);
}
else if(serverInput.startsWith("SENSORACCEPTED")){
System.out.println("Sensor Is Accepted");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
}
public static void main(String args[]){
FireAlarmSensor sensor = new FireAlarmSensor();
sensor.run();
}
}
Server is working perfectly fine in my program. It doesn't crash anytime and first sensor also can connected with the server and it also never get crashed. But when try to connect another sensor to a server by running the FireAlarmSensor.class file, 2nd sensor gives me following exception and crash.
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at sensors.FireAlarmSensor.run(FireAlarmSensor.java:64)
at sensors.FireAlarmSensor.main(FireAlarmSensor.java:96)
I'm running server and all the sensors in same machine using eclipse neon.
Lines from 16 to 27 in Client(Sensor) cause an errors because I haven't uploaded that java files.Please comment or delete them when you running it.
The main method only calls accept once, so it is not surprising that only one client can connect. Try accepting clients in a loop:
private static boolean shouldExit = false;
public static void main(String args[]) {
System.out.println("Sensor Server Is Running");
try (ServerSocket listener = new ServerSocket(port)) {
acceptLoop(listener);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void acceptLoop(ServerSocket listener) throws IOException {
while (!shouldExit) {
// accept() blocks until a connection is made
Socket client = listener.accept();
new sensorHandler(client).start();
}
}
What this will do is just loop forever, accepting new clients until you set shouldExit to be true. The main thread, that is.
I've taken the liberty to make use of the Java 7 try-with-resources statement (try (ServerSocket listener = ...)). It does essentially what your convoluted try-catch-finally did - automatically closes the ServerSocket.

UnknownHostException in Java Client/Server-Programm

The class Server:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server{
private int port;
private Socket client;
private ServerSocket server;
public Server(int port) {
try {
this.port = port;
setServer(new ServerSocket(this.port));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.start();
}
public void start() {
ArrayList<ClientHandler> clients = new ArrayList<>();
ExecutorService executor = Executors.newFixedThreadPool(20);
System.out.println("Server started...");
while (true) {
try {
setClient(null);
setClient(getServer().accept());
if (getClient() != null) {
ClientHandler handler = new ClientHandler(getClient());
System.out.println("Client connected...");
clients.add(handler);
executor.execute(handler);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Server server = new Server(4567);
}
public Socket getClient() {
return client;
}
public void setClient(Socket client) {
this.client = client;
}
public ServerSocket getServer() {
return server;
}
public void setServer(ServerSocket server) {
this.server = server;
}
}
Now, my Question is, is there a Problem in the class, which causes the UnknownHostException? I already tried to debug, but the problem lies in the class Client
The Class Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client{
private String kennung;
private Socket server;
private String host;
private int port;
public Client(String kennung, String host, int port){
setKennung(kennung);
setHost(host);
setPort(port);
try {
setServer(new Socket(this.host, this.port));
//Scanner reader = new Scanner(this.server.getInputStream());
PrintWriter writer = new PrintWriter(getServer().getOutputStream(), true);
Scanner sc = new Scanner(System.in);
writer.println("The Client");
/*while(true){
boolean next = reader.hasNext();
if (next) {
String line = reader.nextLine();
if(!line.equals(null)){
System.out.println("From another one: " + line);
}
}
writer.println(sc.next());
}*/
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if( server != null){
try {
server.close();
} catch (IOException e) {
//ignore -> Server getting closed
}
}
}
}
public String getKennung() {
return kennung;
}
public void setKennung(String kennung) {
this.kennung = kennung;
}
public Socket getServer() {
return server;
}
public void setServer(Socket server) {
this.server = server;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public static void main(String[] args) {
Client testClient = new Client("testClient", "127.0.0.1", 4567);
System.out.println("Client created");
}
}
And Last, but not least: The Class ClientHandler that implements Runnable and runs a Thread, where I read the input from the client and write it to the server.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
public class ClientHandler implements Runnable {
public ArrayBlockingQueue<String> messsages;
Socket client;
public ClientHandler(Socket client) {
this.messsages = new ArrayBlockingQueue<>(20);
this.client = client;
}
#Override
public void run() {
PrintWriter writer = null;
Scanner reader = null;
try {
reader = new Scanner(this.client.getInputStream());
writer = new PrintWriter(this.client.getOutputStream(), true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line = "";
while (!line.equals(".bye")) {
//System.out.println("Got something? " + reader.hasNext());
line = reader.nextLine();
if (reader.hasNext()) {
if (!line.equals(null)) {
System.out.println("Vom Client: " + line);
}
}
//writer.println("Admin-Message"); // Zum Testen
}
}
}
Thanks to everybody, who helps me with this problem.

Unknown host RMI java

I get an unknown host error when I try to start an RMI server
here. The error is unknown host. Actually, I'm just a beginner in RMI and sockets programming in JAVA. Can you please provide me with some tutorials
concerning my problem.
My interface code:
package ApplicationServer;
import java.io.File;
import java.rmi.RemoteException;
import java.sql.ResultSet;
public interface Méthodes {
public String authentification(String login, String mdp) throws RemoteException;
public ResultSet selection(String requete) throws RemoteException;
public int miseAjour(String requete) throws RemoteException;
public String envoyerFichier(File fichier) throws RemoteException;
}
In this class I have all the methods that I need in my program:
package ApplicationServer;
import java.io.File;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Traitements extends UnicastRemoteObject implements Méthodes {
private Connection cnx;
private Statement stm;
private ResultSet rst;
private int rs;
public void setCnx(Connection cnx) {
this.cnx = cnx;
}
public void setStm(Statement stm) {
this.stm = stm;
}
public void setRst(ResultSet rst) {
this.rst = rst;
}
public void setRs(int rs) {
this.rs = rs;
}
protected Traitements() throws RemoteException {
super();
// TODO Auto-generated constructor stub
}
#Override
public String authentification(String login, String mdp) throws RemoteException {
// TODO Auto-generated method stub
try {
setCnx(null);
setStm(null);
setRst(null);
Class.forName("com.mysql.jdbc.Driver");
cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/banque","root","");
stm=cnx.createStatement();
rst=stm.executeQuery("select md5('"+mdp+"');");
while(rst.next()){
mdp=rst.getString(1);
}
stm.clearBatch();
stm=cnx.createStatement();
setRst(null);
String Query = "select * from utilisateurs where login like '"+login+"' and motdepasse like '"+mdp+"';";
rst=stm.executeQuery(Query);
int id = 0;
String nm = null;
String prm = null;
while(rst.next()){
id = rst.getInt("id");
nm = rst.getString("nom");
prm = rst.getString("prenom");
}
if(id>0 && nm!=null && prm!=null){
return id+" "+nm+" "+prm;
}
}catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public ResultSet selection(String requete) throws RemoteException {
try{
setCnx(null);
setStm(null);
setRst(null);
Class.forName("com.mysql.jdbc.Driver");
cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/banque","root","");
stm=cnx.createStatement();
rst=stm.executeQuery(requete);
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rst;
}
#Override
public int miseAjour(String requete) throws RemoteException {
try{
setCnx(null);
setStm(null);
setRs(0);
Class.forName("com.mysql.jdbc.Driver");
cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/banque","root","");
stm=cnx.createStatement();
rs=stm.executeUpdate(requete);
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
#Override
public String envoyerFichier(File fichier) throws RemoteException {
// TODO Auto-generated method stub
return null;
}
}
This is the main class that runs the server:
package ApplicationServer;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
int port=12345;
String url="rmi://serveur:"+port+"/reference";
LocateRegistry.createRegistry(port);
Traitements srv = new Traitements();
Naming.rebind(url, srv);
JOptionPane.showMessageDialog(null, "Serveur Lance :");
} catch (RemoteException | MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are supposed to replace serveur with a real hostname in that code.
However it's far better to use localhost in the RMI URL when binding. The Registry has to be local to the host anyway so there's no point in using anything else.

Need help on a simple server/multiple client chat application

this is the scenario .. i have 2 clients connected to a server.. i want them to be able to chat with eachother. After a couple of messages i get this error.
Exception in thread "Thread-0" java.lang.ClassCastException:
java.io.ObjectStreamClass cannot be cast to message.Mesaj
at server.ServerThread.readAndWrite(ServerThread.java:43)
at server.ServerThread.run(ServerThread.java:61)
java.io.StreamCorruptedException: invalid type code: 00
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at server.ServerThread.readAndWrite(ServerThread.java:43)
at server.ServerThread.run(ServerThread.java:61)
This is the client:
package client;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
import message.Mesaj;
public class Client {
public static int port=4321;
public static Socket socket;
public static ObjectOutputStream oo;
public static ObjectInputStream oi;
public static Scanner sc;
public Client() throws IOException{
socket = new Socket ("localhost",4321);
oi = new ObjectInputStream(socket.getInputStream());
oo = new ObjectOutputStream(socket.getOutputStream());
}
public static void listen() throws ClassNotFoundException, IOException{
while(true){
Mesaj m = (Mesaj) oi.readObject();
if(m!=null){
System.out.println("mesajul este: " + m.getMesaj());
}
}
}
public static void write() throws IOException{
sc= new Scanner(System.in);
while(true){
String trimite= sc.nextLine();
Mesaj m = new Mesaj();
m.setMesaj(trimite);
oo.writeObject(m);
oo.flush();
}
}
public static Thread t = new Thread(){
public void run(){
try {
listen();
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public static Thread t2 = new Thread(){
public void run(){
try {
write();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public static void main(String[] args) throws IOException{
new Client();
t.start();
t2.start();
}
This is the Server:
package server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
public int port;
public static Socket socket;
public static ServerSocket serverSocket;
public Server() throws IOException{
this.port=4321;
serverSocket = new ServerSocket(port);
}
public static void main (String [] args){
try {
new Server();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Server functionabil..asteptam conexiune client");
while(true){
try {
socket= serverSocket.accept();
ServerThread st= new ServerThread(socket);
st.start();
System.out.println("Conexiune realizata -client conectat");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
..and this is the Server Thread:
package server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import message.Mesaj;
public class ServerThread extends Thread {
boolean running;
public static ObjectOutputStream oo;
public static ObjectInputStream oi;
public static Mesaj m;
public static Socket socket;
public ServerThread(Socket socket) throws ClassNotFoundException{
try {
running=true;
this.socket=socket;
oo = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void readAndWrite() throws ClassNotFoundException, IOException{
oi = new ObjectInputStream(socket.getInputStream());
while(true){
m= (Mesaj) oi.readObject();
if(m!=null){
oo.writeObject(m);
oo.flush();
System.out.println(m.getMesaj());
}
}
}
public void run(){
System.out.println("Server Thread contectat");
try {
readAndWrite();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
EDIT:
This is the message class:
package message;
import java.io.Serializable;
public class Mesaj implements Serializable {
private String mesaj;
public String getMesaj() {
return mesaj;
}
public void setMesaj(String mesaj) {
this.mesaj = mesaj;
}
}
You having concurrency issues.
Both serverthreads access the same static outputstream, meaning that there is a change for corruption as Object streams aren't designed for this.
In ServerThread, remove static from all the variables and the method "readAndWrite".
public ObjectOutputStream oo;
public ObjectInputStream oi;
public Mesaj m;
public Socket socket;
...
public void readAndWrite() throws ClassNotFoundException, IOException{
If you want to access the output streams from multiple threads, you should synchronize on them.

Categories

Resources