Reputation: 51
i'm developing a software that with a Socket, sets a connection with a server(where I installed PgAdmin for DB). I create the client e server code and they run perfectly but I don't know how to send data via socket when the user do some action. The software is like a social network, where users login and see their info and news from the other users that are logged.
public class LoginForm {
private JTextField EditUsername;
private JTextField EditEmail;
private static Client client;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
client = new Client();
client.connectToServer();
LoginForm window = new LoginForm();
window.Loginframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public LoginForm() {
initialize();
}
...
...
String username = "USER"; client.SendToServer(username );
this is my login form where firstly connect client to server. Then when I need to send info to server I don't know what i need to do !!!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private BufferedReader in;
private PrintWriter out;
private static Socket socket;
private static String number ="0" ;
/**
* Constructs the client by laying out the GUI and registering a
* listener with the textfield so that pressing Enter in the
* listener sends the textfield contents to the server.
*/
public Client() {
}
public void connectToServer() throws IOException {
String host = "localhost";
int port = 4000;
InetAddress address;
try {
address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "1";
String sendMessage = number;
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void SendToServer(String username){
}
}
So this is the client that receive the string User but What I need to do ??? create another socket connection ? Please help me, sockets are driving me mad. I must user socket(I know RMI is much better)
Upvotes: 2
Views: 1675
Reputation: 14658
Very short answer: you need to make private static Socket socket;
, private BufferedReader in;
and private PrintWriter out;
local variables inside connectToServer()
method. Also, private static Client client;
inside your main method.
Longer answer:
Client server multithread Socket
This is bit debatable because there is nothing like "multithreaded socket", you will either have a "multi-threaded server" or "single-threaded server", which basically means that either your server would capable of handling/processing concurrent connections or it would be not.
Now, suppose at server side you have just Socket clientSocket = serverSocket.accept();
and then you are always reading and writing over clientSocket
object then you have "single-threaded server" which basically means that until first request is not completed, your second request would remain in queue. If you want to create a "multi-threaded server" then you will create a new thread each time and then do the processing, here basically you would have a new socket representing a unique client connection. Below is a sample "multi-threaded server" code.
Now, coming at client side, you will specify your server socket details, the way you are doing socket = new Socket(address, port);
, so basically a new socket will be opened at your "client side" using some random port number at your end (please note that this is not a random server port number, at your end JVM will get a random "available" port number from OS for communication), and that socket object would represent a unique connection with the server. So, then you will access output stream on that socket (to send data to server) and input stream (to read data from server).
Now, here is the catch of your case - at client side, either you can keep that socket open and use it for all server communications, like user has clicked once, communicate using that socket, and then again use that for next click etc. (please note that I am just putting this to explain), OR whenever you want a communication you will create a new socket at your end and communicate. Now, typically a user click at GUI will contact server and server processes that request in a new thread, so your server (the one with which you want to communicate from your server) communication code will be ran in a new thread, and in your case code in connectToServer()
, only thing you need to make sure that each time you are creating a new socket at your server's end and not making it static and reusing same socket for each request.
Now, this is the raw case you are doing, if you use Spring or some other frameworks/API then you can get connection pooling for free.
So this is the client that receive the string User but What I need to do ??? create another socket connection ?
Yes, you should create a new client socket each time and use that, either implicitly or by creating a new thread to do communication, I have explained above how is your case; and whole point is that each time you should have a new socket at your end for communicating with server.
Please help me, sockets are driving me mad.
Don't worry just understand basic and you will be fine. Best is to read this or complete trail itself.
I must user socket(I know RMI is much better)
You can't compare like this, in the end whether it is RMI, CORBA, RPC etc. etc., there will be a socket at client side and there will be a socket at server side. Just in case - server side socket + client side socket = unique connection between server and client.
Same "multi-threaded server" code:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import com.learn.Person;
/**
* @author himanshu.agrawal
*
*/
public class TestWebServer2 {
public static void main(String[] args) throws IOException {
startWebServer();
}
/**
* test "backlog" in ServerSocket constructor
test -- If <i>bindAddr</i> is null, it will default accepting
* connections on any/all local addresses.
* @throws IOException
*/
private static void startWebServer() throws IOException {
InetAddress address = InetAddress.getByName("localhost");
ServerSocket serverSocket = new ServerSocket(8001, 1, address);
// if set it to 1000 (1 sec.) then after 1 second porgram will exit with SocketTimeoutException because server socket will only listen for 1 second.
// 0 means infinite
serverSocket.setSoTimeout(/*1*/0000);
while(true){
/*Socket clientSocket = serverSocket.accept();*/ // a "blocking" call which waits until a connection is requested
System.out.println("1");
TestWebServer2.SocketThread socketThread = new TestWebServer2().new SocketThread();
try {
socketThread.setClientSocket(serverSocket.accept());
Thread thread = new Thread(socketThread);
thread.start();
System.out.println("2");
} catch (SocketTimeoutException socketTimeoutException) {
System.err.println(socketTimeoutException);
}
}
}
public class SocketThread implements Runnable{
Socket clientSocket;
public void setClientSocket(Socket clientSocket) throws SocketException {
this.clientSocket = clientSocket;
//this.clientSocket.setSoTimeout(2000); // this will set timeout for reading from client socket.
}
public void run(){
System.out.println("####### New client session started." + clientSocket.hashCode() + " | clientSocket.getLocalPort(): " + clientSocket.getLocalPort()
+ " | clientSocket.getPort(): " + clientSocket.getPort());
try {
listenToSocket(); // create this method and you implement what you want to do with the connection.
} catch (IOException e) {
System.err.println("#### EXCEPTION.");
e.printStackTrace();
}
}
}
}
Upvotes: 3