Hi I am new to java client server programming, and I have this modification of a simple program. What I am trying to do is create 2 sockets within the same client, which I then want to use to access 2 sockets on 2 different servers.
The server responds with a very simple String, which is then written into a file and displayed to console. This works fine for whichever sockets code I put first. i.e. if i put clientsocket1 code on top, it receives correctly, but clientsocket2 doesn't get anything.
Vice versa if I flip the order.
Im testing it all on my own computer so I'm using default IP address "0.0.0.0" and different port numbers for the servers.
What could be the issue here?
public static class CustomerClient extends Thread {
private Socket clientSocket1;
private Socket clientSocket2;
String serverInput1;
String serverInput2;
String clientCustomerId;
public CustomerClient(String customerId, String IPAdress1,
int portNumber1, String IPAdress2, int portNumber2) {
try {
clientCustomerId = customerId;
clientSocket1 = new Socket(IPAdress1, portNumber1);
clientSocket2 = new Socket(IPAdress2, portNumber2);
}
catch (UnknownHostException ex) {
System.out.println("connection error " + ex);
} catch (IOException ex) {
System.out.println("Some other exception" + ex);
} catch (Exception ex) {
System.out.println("Some other final exception" + ex);
}
}
public void run() {
try {
DataOutputStream outToServer = new DataOutputStream(
clientSocket1.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket1.getInputStream()));
while ((serverInput1 = inFromServer.readLine()) != null) {
BufferedWriter br = new BufferedWriter(new FileWriter(
tempFile, true));
br.write(serverInput1);
br.newLine();
// br.append(modifiedSentence);
System.out.println("FROM SERVER: " + serverInput1);
br.close();
}
DataOutputStream outToServer2 = new DataOutputStream(
clientSocket2.getOutputStream());
BufferedReader inFromServer2 = new BufferedReader(
new InputStreamReader(clientSocket2.getInputStream()));
while ((serverInput2 = inFromServer2.readLine()) != null) {
BufferedWriter br = new BufferedWriter(new FileWriter(
tempFile, true));
br.write(serverInput2);
br.newLine();
// br.append(modifiedSentence);
System.out.println("FROM SERVER: " + serverInput2);
br.close();
}
} catch (IOException ex) {
} catch (Exception e) {
System.out.println("Error" + e);
} finally {
try {
clientSocket1.close();
clientSocket2.close();
} catch (Exception e) {
System.out.println("Error in closing the connection" + e);
}
}
}
}
Isn't, in your case, the client also a server? Because a normal client only connects to one server and that server can handle multiple clients. So, if you want your client to have multiple "connections" to your server, you have two possibilities:
Make your client a server itself by giving it a ServerSocket object or
Create a kind of protocol, which serializes data in this connection and distributes it correctly
Related
I try to create a chatbox in java thanks to socket. My project was working when I use the terminal but now i try to connect this part with my GUI. For now my project is separated in 2 parts clients and server.
On my GUI part:
First I have a Preframe (The user enter an username and click on enter). If the username is valid (no '#' and contain at least 2 letters), I open the connection with this function:
public void connection(String username){
Socket socket = null;
try
{
socket = new Socket("localhost",2222);
clientSocket = socket;
os= new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
inputLine = new BufferedReader(new InputStreamReader(is));
if (clientSocket != null && os != null && is != null) {
try {
/* Create a thread to read from the server. */
new Thread(new IncomingReader()).start();
while (!closed) {
os.println(inputLine.readLine().trim());
System.out.println(inputLine.readLine().trim());
}
/*
* Close the output stream, close the input stream, close the socket.
*/
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}catch (UnknownHostException e) {
System.err.println("Don't know about host " + "localhost");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host "+ "localhost");
}
}
Here is the thread that I start:
public class IncomingReader implements Runnable{
#Override
public void run() {
/*
* Keep on reading from the socket till we receive "Bye" from the * server. Once we received that then we want to break.
*/
String responseLine;
try {
while ((responseLine = inputLine.readLine()) != null) {
//chatBox.append(responseLine);
System.out.println(responseLine);
if (responseLine.indexOf("*** Bye") != -1)
break;
}
closed = true;
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
On server side:
I accept the connection
while (true) {
try {
clientSocket = serverSocket.accept();
if(threads.isEmpty()){
clientThread t = new clientThread(clientSocket,threads,names);
t.start();
threads.add(t);
}else{
clientThread t = new clientThread(clientSocket,threads,names);
t.start();
threads.add(t);
}
if (threads.size() == maxClientsCount) {
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Server too busy. Try later.");
os.close();
clientSocket.close();
}
} catch (IOException e) {
System.out.println(e);
} //System.err.println("Couldn't get I/O for the connection to the host ");
}
I create a new clientThread:
public void run() {
LinkedHashSet<clientThread> threads = this.threads;
try {
/*
* Create input and output streams for this client.
*/
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
System.out.println(is.readLine().trim());
String name = is.readLine().trim();
System.out.println(name);
/* Welcome the new the client. */
os.println("Welcome " + name + " to our chat room.\nTo leave enter /quit in a new line.");
For now all I notice is when I try to read the name, I can't and then my application freeze. Why is it not working?
Ps: I'm not really good with socket and network in general.
I'm trying to make a basic client <-> server connection in Java. When trying to write to the server, the client sends the details correctly, and the server stalls on reading it until the client output stream is closed. Though, once the output stream is closed it apparently closes the socket, and due to that the server can't reply to the client. Here's the main snippet of code that handles this interaction.
Client:
private void sendCmd(String cmd) {
String infoToSend = cmd;
try {
socket = new Socket(hostname, port);
System.out.println("Trying to send: " + com.sun.org.apache.xml.internal.security.utils.Base64.encode(infoToSend.getBytes()));
out = new DataOutputStream(socket.getOutputStream());
out.writeBytes(com.sun.org.apache.xml.internal.security.utils.Base64.encode(infoToSend.getBytes()));
out.flush();
System.out.println("Socket is flushed");
System.out.println("Waiting for Data");
InputStream is = socket.getInputStream();
System.out.println("Trying to get data");
BufferedReader input = new BufferedReader(
new InputStreamReader(is)
);
String line;
while((line = input.readLine()) != null) {
System.out.println(line);
}
socket.close();
} catch (IOException e) { e.printStackTrace(); }
}
Server:
public void run() {
System.out.println("Got Connection");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new DataOutputStream(socket.getOutputStream());
String response;
System.out.println("Response:");
String decode = "";
while ((response = in.readLine()) != null) {
try {
decode = new String(Base64.decode(response));
} catch (Base64DecodingException e) {
e.printStackTrace();
}
}
System.out.println("Decoded: " + decode);
out.writeBytes("We got your message!");
out.flush();
out.close();
} catch (IOException e) { System.out.println("Fail"); e.printStackTrace(); }
Would anyone be able to guide me on how to fix this error. Sorry if it's super easy and I'm just unable to see it.
Sending
socket.shutdownOutput();
solved the issue.
This may be a stupid question, but here goes.
Im writing this chat program, where there is a server, and clients that can connect to it. I want to implement private messaging into the program, but I don't know how to get the clients to directly connect to eachother. For the server, I used a ServerSocket, which runs on a single port. To get that to work, I needed to forward a port to the server. Is there a way to get the clients to wait for connections, without forwarding a port to them?
Thanks
The whole point of TCP/IP is that a single client connects to a predefined port on a server. So yes, you'll also need to have a ServerSocket on the client that's going to accept the direct connection. You'll almost always run into trouble with port forwarding and the like, which is why UPnP was invented one day.
What you are trying to do is 'peer to peer' connectivity, aka P2P, which is always, by its very definition, plagued by firewalling problems. As such it's usually, especially for a chat, easier to use the central server as 'switchboard' server and relay the private messages as well.
I've written not long time ago a template for multiple client - server application, that might help you to solve your problem. The rest of your question was already answerd by #Niels, I think ;)
import java.net.*;
import java.io.*;
class ServeConnection extends Thread {
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
public ServeConnection(Socket s) throws IOException {
// init connection with client
socket = s;
try {
in = new BufferedReader(new InputStreamReader(
this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Couldn't get I/O.");
System.exit(1);
}
start();
}
public void run() {
System.out.println("client accepted from: " + socket.getInetAddress()
+ ":" + socket.getPort());
// get commands from client, until is he communicating or until no error
// occurs
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null) {
System.out.println("request: " + inputLine);
outputLine = inputLine;
out.println("I've recived "+outputLine);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("server ending");
out.close();
try {
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server {
public static void svr_main(int port) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
System.out.println("Server ready");
try {
while (true) {
Socket socket = serverSocket.accept();
try {
new ServeConnection(socket);
} catch (IOException e) {
System.err.println("IO Exception");
}
}
} finally {
serverSocket.close();
}
}
}
class Client {
static Socket echoSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
public static void cli_main(int port, String servername) throws
IOException {
try {
echoSocket = new Socket(servername, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + servername);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + servername);
System.exit(1);
}
System.out.println("Client ready!");
while (true) {
inputLine = (in.readLine().toString());
if (inputLine == null) {
System.out.println("Client closing!");
break;
}
// get the input and tokenize it
String[] tokens = inputLine.split(" ");
}
out.close();
in.close();
echoSocket.close();
System.out.println("Client closing");
}
}
public class MyClientServerSnippet{
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("Client: java snippet.MyClientServerSnippet<hostname> <port>");
System.err.println("Server: java snippet.MyClientServerSnippet<port>");
System.exit(1);
}
else if (args.length > 1) {
System.out.println("Starting client...\n");
Client client = new Client();
client.cli_main(3049, "127.0.0.1");
} else {
System.out.println("Starting server...\n");
Server server = new Server();
server.svr_main(3049);
}
}
}
I am new to java TCP socket. I tried to implement a server and a client. So the server should check input (do something) and send string to client. The client should send string to the server and look for an input string from the server (and do something). Both should loop checking and sending all the time if something new is available.
The client can send data to the server, the server receives it an can display/process this data.
But the data from the server isn't displayed by the client. Can someone tell me why the client isn't receiving the string from the server? Any better ideas to do endless loop? There will be only one client and one server.
while true:
server out------> send String-----> in client
in<----- sent String <------ out
this is the simplified server part:
public class MainActivity extends Activity {
Socket client;
ServerSocket server;
int serverport = 54321;
String inputData = null;
BufferedReader in;
PrintWriter out;
String outputData;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(setupConnection).start();
}
private Runnable setupConnection = new Thread() {
public void run() {
try {
server = new ServerSocket(serverport);
while (true) {
client = server.accept();
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
inputData = in.readLine();
InputStream inStream = new ByteArrayInputStream(inputData.getBytes());
in.close();
if (inputData != null) {
System.out.println(TAG + "-----Incoming Message---- " + inputData);
//this is working String is shown
} }
out.write("nothing to do?");
out.flush();
out.close();
}
} catch (SocketException e) {
Log.v(TAG, "SocketException: " + e);
e.printStackTrace();
} catch (IOException e) {
Log.v(TAG, "IOException: " + e);
e.printStackTrace();
}
}
the simplified client looks like this:
public class testClass {
public static void main(String[] args) throws IOException, InterruptedException {
Socket socket = null;
String host = "127.0.0.1";
int port = 54321;
PrintWriter out = null;
BufferedReader in = null;
while (true) {
try {
socket = new Socket(host, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println(TAG + "Error: " + e);
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.out.println(TAG + "Error: " + e);
System.err.println("Couldn't get I/O for " + "the connection to: localhost.");
System.exit(1);
}
out.println("Hello, is it me you're looking for...");
out.flush();
String input = in.readLine();
System.out.println("Input: " + input);
in.close();
out.close();
}
}
}
If readLine() returns null,the peer has closed the connection, and you must do likewise. And stop reading.
if you want implement this code in android , you faces many problems:
you can find the solution in this link:
Post JSON in android
in the following code may be fix this problem:
HttpPost post = new HttpPost("http://xxxxxx");
DefaultHttpClient httpClient = new DefaultHttpClient();
post.setEntity(new ByteArrayEntity(json.toString().getBytes()));
HttpResponse response = httpClient.execute(post);
return EntityUtils.toString(response.getEntity());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
System.out.println(">>>>>>>" + e.getMessage());
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println(">>>>>>>" + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
System.out.println(">>>>>>>" + e.getMessage());
}
Hello guys I am trying to do an echo Server by java but it is nnot working .. .I don't know why .. but it seems like the server is waiting the client and the client is waiting the server ... so they can't deliver the infromation to each other ..
here is the code
for the Server
ServerSocket server = null;
try {
server = new ServerSocket(3333);
System.out.println("Listening on 3333");
} catch (IOException ex) {
System.out.println("Error can't connect to 3333");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = server.accept();
} catch (IOException ex) {
System.out.println("Accept fail");
System.exit(1);
}
PrintWriter out = null;
try {
out = new PrintWriter(clientSocket.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(JavaApplication20.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(JavaApplication20.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String inputLine, outputLine;
while(!(inputLine=br.readLine()).equals("bye"))
{
out.print("echo: " + inputLine);
}
out.close();
br.close();
clientSocket.close();
server.close();
System.out.println("Server Exited");
and here is the code for the client
Socket client = null;
try {
client = new Socket("localhost", 3333);
System.out.println("Connected on 3333");
} catch (UnknownHostException ex) {
System.out.println("Couldn't connect to the server");
System.exit(1);
} catch (IOException ex) {
Logger.getLogger(KnockKnockClient.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter out = null;
BufferedReader in = null;
BufferedReader stdIn = null;
try {
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException ex) {
Logger.getLogger(KnockKnockClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(KnockKnockClient.class.getName()).log(Level.SEVERE, null, ex);
}
stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer, fromUser;
while((fromUser=stdIn.readLine())!=null)
{
System.out.println("From user: "+ fromUser);
out.print(fromUser);
fromServer=in.readLine();
System.out.println(fromServer);
}
out.close();
stdIn.close();
in.close();
client.close();
System.out.println("client Exited");
Any Help with that ??
You're sending some string from the client ("Hello" for example), and you're trying to read it with readLine() on the server (and vice versa). readLine() will only return once it finds an EOL character, or once the input stream is closed.
Since the client doesn't send any EOL char, the server waits indefinitely, and the client also because it waits for the answer from the server.
Send "Hello\n", and it will work better.
After out.print(fromUser); use out.flush() in your client and server. flush will make sure it will right to the socket.
while((fromUser=stdIn.readLine())!=null)
{
System.out.println("From user: "+ fromUser);
out.print(fromUser);
out.flush();
fromServer=in.readLine();
System.out.println(fromServer);
}
out.close();
stdIn.close();
in.close();
client.close();
Regarding flush, Extracted from java doc.
Flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.
If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.