I use a thread to serve the client but when I remove the command handler.out.flush (on Server class), the thread hangs. I've tried searching on google but still not helping. I think the problem lies in the communications socket but I still have not got the right solution.
I want to make a simple login and registration functions so i used 2 class, Server and MysqlConn. The Server class receives incoming data (user profile - username, password, etc) from the client over the socket. After receiving, the data will be sent to MysqlConn class. The function of MysqlConn class is to check against the data and access my sql database to match them. If data and database match, then login process is succsses.
The format of data sent by the client is:
"login."+"name."+ "password." +"\n";
The following is the contents of Server class:
public class Server {
public static void main(String[] args)throws IOException, InstantiationException,
IllegalAccessException {
ServerSocket servsocket = null;
Socket sock = null;
try {
servsocket = new ServerSocket(28000);
while(true){
sock = servsocket.accept();
System.out.println(servsocket.isBound());
ChatThread thread = new ChatThread(sock);
String portnum = Integer.toString(sock.getPort());
thread.run(portnum);
}
} catch (IOException ioe) {
}
finally{
try {
servsocket.close();
} catch (IOException ioe) {
}
}
}
}
class ChatThread extends Thread{
static Vector<ChatThread> chatthread = new Vector<ChatThread>(10);
private BufferedReader in;
private PrintWriter out;
public ChatThread (Socket socket) throws IOException {
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(
new OutputStreamWriter(socket.getOutputStream())); }
public void run(String portnum){
String line;
synchronized(chatthread) {
chatthread.addElement(this); }
try {
line = in.readLine()+portnum;
String[] teksmasuk = line.split("\\.");
for(int i = 0; i < chatthread.size(); i++) {
synchronized(chatthread) {
ChatThread handler =
(ChatThread)chatthread.elementAt(i);
handler.out.println(line + "\r");
handler.out.flush();
if
(teksmasuk[0].contentEquals("reg")||teksmasuk[0].contentEquals("login")
||teksmasuk[0].contentEquals("logout")) {
if(teksmasuk[0].contentEquals("reg")){
}
else
if(teksmasuk[0].contentEquals("login")){
}
MysqlConn sqlcon = new MysqlConn();
String hasil = sqlcon.register(line);
}
else{
}
}
}
} catch(IOException ioe) {
ioe.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
finally {
synchronized(chatthread) {
chatthread.removeElement(this);
}
}
}
}
MysqlConn class:
public class MysqlConn{
String dbn = "chat_db";
String URL = "jdbc:mysql://localhost/"+dbn ;
String usr = "root";
String pwd = "";
private String result;
boolean checkname = false;
boolean checkemail = false;
boolean checkpass = false;
private Connection con = null;
private String dbnama;
private String dbpass;
public String register(String line) throws InstantiationException,
IllegalAccessException, IOException, ClassNotFoundException{
String[] messagein =
line.split("\\.");
MysqlConn regs = new MysqlConn();
regs.login(messagein);
return result;
}
public void login (String[] messagein) throws InstantiationException,
IllegalAccessException{
if(messagein[0].contentEquals("login")) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(URL,usr,pwd);
Statement statement =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rslset = statement.executeQuery("select * from user");
int rs = statement.executeUpdate("update user set port="+
"'"+messagein[3] +"'" + "where nama = "
+ "'" + messagein[1] + "'" + "and password = " + "'"
+messagein[2] +"'" );
MysqlConn regs = new MysqlConn();
regs.check_status_login(messagein);
} catch (ClassNotFoundException e) {
System.out.println("Error #1:" + e.getMessage());
System.exit(0);
} catch(SQLException e){
System.out.println("Error #2:" + e.getMessage());
System.exit(0);
}
}
}
public void check_status_login (String[] messagein) throws InstantiationException,
IllegalAccessException, ClassNotFoundException{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(URL,usr,pwd);
Statement statement =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rslset = statement.executeQuery("select * from user");
while(rslset.next()) {
String dbname = rslset.getString("nama");
String dbpass = rslset.getString("password");
if((messagein[1].contentEquals(dbnama))){
+ messagein[1]+ "\r" + "Password from database: "+dbpass + "\r" +
"Password from client: "+ messagein[2]+ "\n");
checknama = true;
}
else if (messagein[2].contentEquals(dbpass)){
checkpass = true;
}
}
} catch (SQLException e1) {
+ e1);
}
if (!checknama){
hasil = "gagal";
}
else if (!checkpass)
{
hasil = "gagal";
}
else {
hasil = "login sukses";}
}
}
The java docs clearly say that the constructor you are using for PrintWriter will not cause automatic flushing. This means that you nead to call flush to send data out of the printwriter manually. Alternatively you can do
out = new PrintWriter( new OutputStreamWriter(socket.getOutputStream()) , true );
to enable automatic flushing. I generally prefer to do flush streams manually anyways.
As far as your question regarding your "application gets stuck" , you will need to provide more information such as how many clients connected and what exactly happens before the system hangs
Related
I am creating a program to play chess through the socket. My client is written in Python which is using socket to send data to the server. I receive information only when client program gets closed. Below mentioned is the client code. I am using python socket https://docs.python.org/3/library/socket.html
def youSecond(board):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.11.46', 9999))
run = True
turn = 1
new_msg = True
while run:
renderMap(board)
move = s.recv(1024).decode("utf-8")
if new_msg:
new_msg = False
print("SERVER: ", move)
players[0].play(board, move)
new_msg = True
turn +=1
renderMap(board)
print("Black machine is thinking.....")
myTurn = players[1].play(board, turn).encode("utf-8")
s.send(myTurn)
turn += 1
and my server using Java
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
PrintWriter client;
public ClientHandler(Socket clientSocket, PrintWriter user) {
client = user;
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
System.out.println("tren helllo");
} catch (Exception ex) {
ta_chat.append("Unexpected error... \n");
}
}
#Override
public void run() {
String message, connect = "Connect", disconnect = "Disconnect", chat = "Chat";
String[] data;
try {
while ((message = reader.readLine()) != null) {
System.out.println("duoi helllo");
ta_chat.append("Received: " + message + "\n");
data = message.split(":");
for (String token : data) {
ta_chat.append(token + "\n");
}
if (data[2].equals(connect)) {
tellEveryone((data[0] + ":" + data[1] + ":" + chat));
userAdd(data[0]);
} else if (data[2].equals(disconnect)) {
tellEveryone((data[0] + ":has disconnected." + ":" + chat));
userRemove(data[0]);
} else if (data[2].equals(chat)) {
tellEveryone(message);
try {
FileWriter fw = new FileWriter("C:\\Users\\Admin\\Desktop\\FixCoTuong\\moves.txt");
fw.write(data[1]);
fw.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("sucess");
} else {
ta_chat.append("No Conditions were met. \n");
}
}
} catch (Exception ex) {
ta_chat.append("Lost a connection. \n");
ex.printStackTrace();
clientOutputStreams.remove(client);
}
I try to verify total comment between frontend and database result. since the database can only accessed through VPN, it makes me stuck. I been tried with below code, but the result is empty, the only ssh connected in the console
public class ConnectDB {
private static Connection connection = null;
private static Session session = null;
private static void connectToServer(String dataBaseName) throws SQLException {
connectSSH();
connectToDataBase(dataBaseName);
}
public static void connectSSH() throws SQLException {
String sshHost = "my ssh host";
String sshuser = "my ssh user";
String dbuserName = "username db";
String dbpassword = "pass db";
String SshKeyFilepath = "/Users/mac/.ssh/id_rsa";
int localPort = 8740; // any free port can be used
String remoteHost = "ip db";
int remotePort = 3306;
String localSSHUrl = "localhost";
/***************/
String driverName = "com.mysql.jdbc.Driver";
try {
java.util.Properties config = new java.util.Properties();
JSch jsch = new JSch();
session = jsch.getSession(sshuser, sshHost, 22);
jsch.addIdentity(SshKeyFilepath);
config.put("StrictHostKeyChecking", "no");
config.put("ConnectionAttempts", "3");
session.setConfig(config);
session.connect();
System.out.println("SSH Connected");
Class.forName(driverName).newInstance();
int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort);
System.out.println("localhost" + assinged_port + " -> " + remoteHost + ":" + remotePort);
System.out.println("Port Forwarded");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void connectToDataBase(String dataBaseName) throws SQLException {
String dbuserName = "username db";
String dbpassword = "pass db";
int localPort = 8740; // any free port can be used
String localSSHUrl = "ip db"; //since ssh connected i guess to put ip db
try {
//mysql database connectivity
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setServerName(localSSHUrl);
//dataSource.setPortNumber(localPort);
dataSource.setUser(dbuserName);
dataSource.setAllowMultiQueries(true);
dataSource.setPassword(dbpassword);
dataSource.setDatabaseName(dataBaseName);
connection = dataSource.getConnection();
System.out.print("Connection to server successful!:" + connection + "\n\n");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void closeConnections() {
CloseDataBaseConnection();
CloseSSHConnection();
}
public static void CloseDataBaseConnection() {
try {
if (connection != null && !connection.isClosed()) {
System.out.println("Closing Database Connection");
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void CloseSSHConnection() {
if (session != null && session.isConnected()) {
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
// works ONLY FOR single query (one SELECT or one DELETE etc)
public static ResultSet executeMyQuery(String query, String dataBaseName) {
ResultSet resultSet = null;
try {
connectToServer(dataBaseName);
Statement stmt = (Statement) connection.createStatement();
resultSet = stmt.executeQuery(query);
System.out.println("Database connection success");
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
public static void DeleteOrganisationReferencesFromDB(String organisationsLike) {
try {
connectToServer("ServerName");
Statement stmt = (Statement) connection.createStatement();
ResultSet resultSet = stmt.executeQuery("select * from DB1");
String organisationsToDelete = "";
List<String> organisationsIds = new ArrayList<String>();
// create string with id`s values to delete organisations references
while (resultSet.next()) {
String actualValue = resultSet.getString("id");
organisationsIds.add(actualValue);
}
for (int i = 0; i < organisationsIds.size(); i++) {
organisationsToDelete = " " + organisationsToDelete + organisationsIds.get(i);
if (i != organisationsIds.size() - 1) {
organisationsToDelete = organisationsToDelete + ", ";
}
}
stmt.executeUpdate(" DELETE FROM `DB1`.`table1` WHERE `DB1`.`table1`.`organisation_id` in ( " + organisationsToDelete + " );");
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
}
public static List<String> getOrganisationsDBNamesBySubdomain(String organisationsLike) {
List<String> organisationDbNames = new ArrayList<String>();
ResultSet resultSet = executeMyQuery("select `DB`.organisation.dbname from `DB1`.organisation where subdomain like '" + organisationsLike + "%'", "DB1");
try {
while (resultSet.next()) {
String actualValue = resultSet.getString("dbname");
organisationDbNames.add(actualValue);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
return organisationDbNames;
}
public static List<String> getAllDBNames() {
// get all live db names incentral DB
List<String> organisationDbNames = new ArrayList<String>();
ResultSet resultSet = executeMyQuery("show databases", "DB1");
try {
while (resultSet.next()) {
String actualValue = resultSet.getString("Database");
organisationDbNames.add(actualValue);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
return organisationDbNames;
}
public static void deleteDataBasesByName(List<String> DataBasesNamesList) {
try {
connectSSH();
int dataBasesAmount = DataBasesNamesList.size();
for (int i = 0; i < dataBasesAmount; i++) {
connectToDataBase(DataBasesNamesList.get(i));
Statement stmt = (Statement) connection.createStatement();
stmt.executeUpdate("DROP database `" + DataBasesNamesList.get(i) + "`");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
CloseDataBaseConnection();
closeConnections();
}
}
but the result in console, no sign that query is executed
*the query is on another file
conn.connectSSH();
conn.executeMyQuery("select shade_item FROM nubr_product_shade WHERE shade_id=1", "database_name");
SSH Connected
localhost8740 -> 172.xx.x.xx:3306
Port Forwarded
Why you not do that with operating system utils ?
for example (MySQL Database) :
ssh -R 3306:127.0.0.1:3306 username#server.com -NnT
now jdbc connection to localhost with port 3306 .
I have created a quizServer application in java swing that connects to multiple clients through a socket. I am able to send data to the server from each client simultaneously through the socket connection but when I try to send data to the clients from the server then it is being received by only 1 client. How can I modify the code to send data to all the clients listening on the socket at the same time? Any code/pseudo-code will be appreciated.
This is my NetworkClient class:
public class NetworkClient {
PrintWriter os = null;
Socket s1 = null;
String line = null;
BufferedReader br = null;
BufferedReader is = null;
InetAddress address = null;
void initClient() {
try {
address = InetAddress.getLocalHost();
System.out.println(address);
} catch (UnknownHostException ex) {
Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
s1 = new Socket(address, 8888); // You can use static final constant PORT_NUM
br = new BufferedReader(new InputStreamReader(System.in));
is = new BufferedReader(new InputStreamReader(s1.getInputStream()));
os = new PrintWriter(s1.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
System.err.print("IO Exception");
}
}
void sendVal(int data) {
os.println(data);
os.flush();
}
void close() {
try {
is.close();
os.close();
br.close();
s1.close();
} catch (Exception ex) {
Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Here is my Server class:
public class QuizServer {
QuizJFrame frame;
ServerThread st;
void initServer(QuizJFrame frm) {
frame = frm;
Socket s = null;
ServerSocket ss2 = null;
System.out.println("Server Listening......");
try {
ss2 = new ServerSocket(8888); // port number used as 8888
} catch (IOException e) {
e.printStackTrace();
System.out.println("Server error");
}
while (true) {
try {
s = ss2.accept();
System.out.println("connection Established");
st = new ServerThread(s, frm);
st.start();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
This is the server thread class:
class ServerThread extends Thread {
BufferedReader is = null;
PrintWriter os = null;
Socket s = null;
QuizJFrame frame;
String question[] = {"", "QUESTION 1", "QUESTION 2", "QUESTION 3", "QUESTION 4", "END"};
int answer[] = {0, 1, 2, 3, 4};
int index;
public ServerThread(Socket s, QuizJFrame frm) {
this.s = s;
frame = frm;
index = 1;
frame.setQuestion(question[index]);
}
#Override
public void run() {
int option = 0;
try {
is = new BufferedReader(new InputStreamReader(s.getInputStream()));
os = new PrintWriter(s.getOutputStream());
} catch (IOException e) {
System.out.println("IO error in server thread:" + e);
}
try {
while (option > -1) {
try {
option = Integer.parseInt(is.readLine());
os.println(answer[index] == option);
os.flush();
} catch (NumberFormatException e) { //to handle null value
}
System.out.println(result(option));
frame.output(result(option));
}
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
String result(int op) {
if (op == -1) {
return "Client exited";
}
if (answer[index] == op) {
return "Option " + op + " is the correct answer.";
} else {
return "Option " + op + " is incorrect.";
}
}
void nextQues() {
index++;
frame.setQuestion(question[index]);
os.println(-2);
os.flush();
}
}
EDIT : Using List<ServerThread> resolved the issue.
Your server has only one ServerThread variable, and thus can only send data to one socket, the last one added. Instead, consider giving the class an List<ServerThread> variable to allow it to communicate with all the clients. Then in the while loop where you create connections, add each newly created ServerThread to this list.
You'll also need to fix your server's threading issues so that the while (true) loop doesn't block key code.
You'll also need to upgrade the ServerThread class so that the main server object can communicate with its streams.
Also you almost never want to have a class extend Thread. Have it implement Runnable instead.
I am trying to make a client/server connection using SOCKETS.
Server side is Java in Eclipse,
Client side is in Android Studio.
There is some codes in both server and client sides for socket connection.
The connection was SUCCESSFUL yesterday.Today, I tried to connect to server with android app client, I have FAİLED.
When I check connections from netstat -a -n , I saw this:
(When I open the client)
That's weird because I have seen this ports before connection codes work.And the ports increases.
And Server Codes:
public class CapitalizeServer {
static ArrayList<Client> clients = new ArrayList<>();
public static void main(String[] args) throws Exception {
System.out.println("The capitalization server is running.");
int clientNumber = 0;
ServerSocket listener = new ServerSocket(44057);
try {
while (true) {
new Capitalizer(listener.accept(), clientNumber++).start();
}
} finally {
listener.close();
}
}
private static class Capitalizer extends Thread {
private Socket socket;
private int clientNumber;
private String uname,pass;
private boolean checked;
public Capitalizer(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
log("New connection with client# " + clientNumber + " at " + socket);
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String input = in.readLine();
if(input.substring(0, "uname:".length()).equals("uname:")){
this.uname = input.substring(6);
}else{
return; //Programı durdur
}
input = in.readLine();
if(input.substring(0,"pass:".length()).equals("pass:")){
this.pass = input.substring(5);
}else{
return; //Programı durdur
}
if(this.pass != null && !checked){
if(checkPass() == 1){
//Yanıt olumlu olduğu için bağlantı clientlar arasına eklenir.
Client cc = new Client(uname, pass, socket, 0, 1);
clients.add(cc);
checked = true;
}else{
//Yanıt olumuz ise bağlantı koparılır.
socket.close();
log("Socket Closed!" + socket);
checked = true;
}
}
while (true) {
if (input == null || input.equals(".")) {
break;
}
//Mesajlar iletilir.
if(input.substring(0,3)=="com:"){
switch (input.substring(4,5)) {
case "1": //Attack başlat 1 şİMDİLİK SADECE BU SEÇENEK AKTİF
//pHp ile random person belirle. (uname döndürür.)
//clients arrayında olup olmadığını kontrol et.(online mı ve savaşta mı)
//->eğer online ise, savaşta olup olmadığına bak
// eğer savaşta ise saldırılmaz.
// Eğer savaşta değil ise saldır, socket ile onu da savaş alanına al
//->Eğer online değil ise savaşı başlat.Adama da mesaj at.
attack1();
break;
case "2": //Attack başlat 2
break;
case "3": //Attack başlat 3
break;
case "4": //Attack başlat 4
break;
default:
break;
}
}
}
} catch (IOException e) {
log("Error handling client# " + clientNumber + ": " + e);
} finally {
try {
socket.close();
} catch (IOException e) {
log("Couldn't close a socket, what's going on?");
}
log("Connection with client# " + clientNumber + " closed");
}
}
public void attack1(){
try {
// open a connection to the site
URL url = new URL("http://localhost/attack/attack.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print("firstKey=firstValue");
ps.print("&secondKey=secondValue");
// we have to get the input stream in order to actually send the request
//con.getInputStream();
// close the print stream
ps.close();
BufferedReader cin = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = cin.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public int checkPass(){
//Connect to db and check the pass and uname
//Php kodları arasında check işlemini yapan url'yi çalıştır
//Yanıt olumlu ise 1, değilse 0 döndür.
try {
// open a connection to the site
URL url = new URL("http://localhost/userControls/singin.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
//con.setDoInput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print(URLEncoder.encode("uname","UTF-8") + "=" + URLEncoder.encode(uname, "UTF-8"));
ps.print(URLEncoder.encode("&pass=","UTF-8")+ "=" + URLEncoder.encode(pass, "utf-8"));
ps.close();
System.out.println("111111");
BufferedReader cin = new BufferedReader(new InputStreamReader(con.getInputStream()));
System.out.println("222222");
String line = null;
while ((line = cin.readLine()) != null) {
System.out.println(":::::::Geldik la Geldiiiik::::::::: " + line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
private void log(String message) {
System.out.println(message);
}
}
}
And clients first activitys code:
public class SignInMenu extends ActionBarActivity {
Button button18;
EditText et1,et2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signin_menu);
button18 = (Button) findViewById(R.id.button18);
et1 = (EditText) findViewById(R.id.editText);
et2 = (EditText) findViewById(R.id.editText2);
}
public void button18Click(View view){
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("uname",et1.getText().toString());
intent.putExtra("pass",et2.getText().toString());
startActivity(intent);
}
}
I am using WAMP Server.
And there is something weird about it.I cant access localhost using my local ip(192.168.1.36). Only with this: http://localhost/
When i try to connect with my local ip, the error like this:192.168.1.36 refused connection.
Maybe this is about the problem.
So how can i solve this problem?
EDİT:(NEW PROBLEM)
*Problem is about java-php connection now.
My server connects to php for queries.Here is the code for connect to php page.I take error in line "PrintStream ps = new PrintStream(con.getOutputStream());".
And the error says: Connection refused:connect
try{
// open a connection to the site
URL url = new URL("http://192.168.1.35/userControls/singin.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
//con.setDoInput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print(URLEncoder.encode("uname","UTF-8") + "=" + URLEncoder.encode(uname, "UTF-8"));
ps.print(URLEncoder.encode("&pass=","UTF-8")+ "=" + URLEncoder.encode(pass, "utf-8"));
ps.close();
BufferedReader cin = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = cin.readLine()) != null) {
System.out.println(":::::::Worked::::::::: " + line);
}
}/* catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*/ catch (Exception e) {
System.out.println("Eror:" + e.getMessage());
}
How can i solve this second problem?
I want to develop a sever which do following tasks.
1)Accepts request from client1 reads objet and write another object
2)Accepts request from client2 reads objet and write another object
3)Client1 enters info of client2,server has to get the client2 based on info and write an object on client2
Server java
public class Server{
ServerSocket serverSocket ;
Socket socket;
#SuppressWarnings("rawtypes")
public static List<Map> clientList = new ArrayList<Map>();//creating list to store map objects of all clients
// Server socket instantiating
Server(int port) {
try{
serverSocket = new ServerSocket(port);
}catch(Exception e){
e.printStackTrace();
}
}
//server is waiting on listen mode for accepting clients
void serverConnect() {
while (true) {
try {
System.out.println("Server is Waiting for client to connect ");
socket = serverSocket.accept();
socket.setKeepAlive(true);
System.out.println("connected to: "+ socket.getRemoteSocketAddress());
new Thread(new ClientSession(socket)).start();//creating a new thread for every client
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
public static void main(String args[]) throws IOException {
Server server = new Server(5050);
try {
server.serverConnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
ClientSession.java
`public class ClientSession implements Runnable {
Socket clientsocket;
String emailId;
String msg;
String ipaddress;
String phoneNumber;
String sessionId;
String socketAddress;
String calleeInfo;
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Server";
ObjectOutputStream oos;
#SuppressWarnings("rawtypes")
Map globalmap = new HashMap();//creating a hashmap object to store sockets,objectoutputstreamobjects of clients
ClientSession(Socket socket) {
// TODO Auto-generated constructor stub
globalmap.put("clientsockets", socket);
this.clientsocket = socket;
System.out.println("socket--"+socket);
try {
oos = new ObjectOutputStream(clientsocket.getOutputStream());
globalmap.put("oos", oos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
public void run() {
// TODO Auto-generated method stub
System.out.println("A new Thread started");
try {
System.out.println("IN SERVER READ METHOD");
ObjectInputStream ois = new ObjectInputStream(clientsocket.getInputStream());
Map<String, String> map = (Map<String, String>) ois.readObject();
System.out.println("map in servereread"+map);
System.out.println("IN SERVER DECODE METHOD");
msg = map.get("msg");
System.out.println(msg);
emailId = map.get("email");
phoneNumber = map.get("phoneno");
globalmap.put("phoneno", phoneNumber);
globalmap.put("email",emailId);
Server.clientList.add(globalmap);
if (msg.equals("REGISTER")) {
System.out.println("IN DECODE REGISTER");
ipaddress = map.get("ipaddr");
} else if (msg.equals("INVITE")) {
System.out.println("IN DECODE INVITE");
sessionId = map.get("sessionId");
calleeInfo = map.get("calleeInfo");
}
analyze(map);
} catch (Exception e) {
e.printStackTrace();
}
}
private void analyze(Map<String, String> map) {
// TODO Auto-generated method stub
try {
String SQL = null;
System.out.println(msg);
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
Connection conn = DriverManager.getConnection(DB_URL,"username","pwd");
Statement st = conn.createStatement();
SocketAddress socketAddr = clientsocket.getRemoteSocketAddress();
socketAddress = socketAddr.toString();
if (msg.equals("REGISTER")) {
SQL = "INSERT INTO Register (email,phoneNumber,ipaddress,socketaddress) VALUES ('"+ emailId+ "','"+ phoneNumber+ "','"+ ipaddress+ "','" + socketAddress + "')";
System.out.println("SQL statement..." + SQL);
serverWrite();
} else if (msg.equals("INVITE")) {
System.out.println("Connecting to database for invite...");
SQL = "INSERT INTO Invite (sessionid,calleremail,callerphoneNo,calleeInfo) VALUES ('"+ sessionId+ "','"+ emailId+ "','"+ phoneNumber+ "','" + calleeInfo + "')";
System.out.println("SQL statement--" + SQL);
System.out.println("CalleeInfo--" + calleeInfo);
// Retrieve the socket of the destination
String query = "SELECT * FROM Register WHERE email='"+ calleeInfo + "' OR phoneNumber = '" + calleeInfo+ "'";
ResultSet rs = st.executeQuery(query);
System.out.println("ResultSet--" + rs);
if (rs.next()) {
String socketaddr = rs.getString("socketaddress");
String email= rs.getString("email");
String phoneNo= rs.getString("phoneNumber");
String ipadd= rs.getString("ipaddress");
}
for(int i=0;i<Server.clientList.size();i++){
String emailid= (String) Server.clientList.get(i).get("email");
String phone = (String) Server.clientList.get(i).get("phoneno");
if(calleeInfo.equals(emailid) || calleeInfo.equals(phone)){
ObjectOutputStream out1= (ObjectOutputStream) Server.clientList.get(i).get("oos");
System.out.println("ObjectOutputStream----"+out1);
System.out.println("writing on"+Server.clientList.get(i).get("clientsockets"));
System.out.println("map before writing on to client2--"+map);
out1.reset();
out1.writeObject(map);
out1.flush();
break;
}
}
// retrieve socket info from register table based on calleeInfo
// as primary key
}
st.executeUpdate(SQL);
} catch (Exception e) {
e.printStackTrace();
}
}
private void serverWrite() {
// TODO Auto-generated method stub
try {
// Using ObjectOutputStream class to write object
HashMap<String, String> map = new HashMap<String, String>();// Creating an object for HashMap class
if (msg.equals("REGISTER")) {
System.out.println("ObjectOutputStream storing--"+oos);
map.put("msg", "REGISTERED"); // setting a message in HashMap object
System.out.println("sending registered");
oos.writeObject(map);// writing an object on socket
}
/* else if (msg.equals("INVITE")) {
map.put("msg", "CALLING");
System.out.println("sending calling");
}*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
It is going to the client1 socket but its not writing on the client2..Its writing on client1..
Thanks in advance.
The problem is with the client not in the server in this case..but one suggestion is don't create map object as Map map= new Map;.It will take only Strings. just create as Map map=new Map();It will take Strings,arrays and all datatypes.