I'm trying to make a TCP listener on java. The software should act like "Hercules" or SocketTest. Problem is, it's not recieving any connections from other computers or devices. It does connect to Hercules or SocketTest but not to my program.
public class Server3 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
System.out.println(InetAddress.getLocalHost());
serverSocket = new ServerSocket(7165,0,InetAddress.getLocalHost());
} catch (IOException e) {
System.err.println("Could not listen on port: 7165.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("Client connected!");
System.out.println(clientSocket.getRemoteSocketAddress()+" connected\n");
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
clientSocket.setSoTimeout(1000);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine ;
boolean connected = true;
while (connected)
{
try {
inputLine = in.readLine();
System.out.println("Client said : "+inputLine);
if (inputLine == null)
{
System.out.println("Client Disconnected!");
connected = false;
}
}
catch(java.net.SocketTimeoutException e)
{
System.out.println("Timed out trying to read from socket");
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
I also used ServerSocket socket = new ServerSocket(port) but no results.
Is there any configurations to do more than just port ? Is it even possible to make this?
Related
Server application and client application are running in different computers. I want to send some message from client to server. The server should receive it and display. But in my case it's not happening. Nothing happens in server computer when something is sent.
This is my client program:
import java.io.*;
import java.net.*;
public class EchoClient {
//private static final String IP="194.47.46.36";
public EchoClient() {
}
public void establish() {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
//echoSocket = new Socket(InetAddress.getLocalHost(), 8080);
echoSocket = new Socket("195.47.46.76", 4444);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
try {
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
if (userInput.equals("Bye."))
break;
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
} catch (IOException ioe) {
System.out.println("Failed");
System.exit(
-1);
}
}
}
In my client-server application, the client sends message to Server and the Server should display the message. But in my case, the client is only able to send but the server can't achieve it.
I have tried with different port numbers (i.e. 8080, 8000, 4444 etc). It seems that the socket can set up the connection, but I really don't know why the server can't read the input from client.
This is my complete project (I have ignored the main classes for both application here, because I have nothing more than just calling the methods):
EchoServer.java:
package client.server;
import java.io.*;
import java.net.*;
public class EchoServer {
public EchoServer() {
}
public void establish() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Could not listen on port: 1234");
System.exit(-1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed: 1234");
System.exit(-1);
}
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(
clientSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
} catch (IOException ioe) {
System.out.println("Failed in creating streams");
System.exit(-1);
}
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
if (inputLine.equals("Bye.")) {
break;
}
}
} catch (IOException ioe) {
System.out.println("Failed in reading, writing");
System.exit(-1);
}
try {
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
System.out.println("Could not close");
System.exit(-1);
}
}
}
EchoClient.java:
package server.client;
import java.io.*;
import java.net.*;
public class EchoClient {
public EchoClient() {
}
public void establish() {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
//echoSocket = new Socket(InetAddress.getLocalHost(), 1234);
echoSocket = new Socket(InetAddress.getLocalHost(), 8080);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
try {
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
if (userInput.equals("Bye.")) {
break;
}
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
} catch (IOException ioe) {
System.out.println("Failed");
System.exit(
-1);
}
}
}
Your server doesn't write the incoming text to the console but only back to the client which doesn't handle incoming text from the server yet.
(out isn't System.out but Socket.out!)
In your server you are listening with readLine() in whileloop
while ((inputLine = in.readLine()) != null) {
System.out.println("inputLine "+inputLine);
which is nothing but the inputstream from client. The above SOP will print the message from client. Try to flush your streams because it won't print until your buffer is full.
Code seems to be fine. If you write some thing on PrintWriter at both server & client ends, you will get output.
Add below code in server: ( After creating Socket with accept() API)
out.println("Hello from Server");
Add below code in client ( After creating Socket)
out.println("Hello from client");
Other suggestions:
1) Create a thread once you accept a Socket Connection at server and that thread should handle all IO processing
2) You can create thread at client end too after creating Socket with Server. The new thread should handle all IO processing
Apologies as I asked something similar last night, but I have narrowed my problem down. I am wondering how to make my Java TCP Socket Server read in the data sent using the printWriter(out) in the Client code from a GUI as it does from the command line stdin.
I have the following classes as an example and everything works fine until the GUI comes into the equation. The data is being sent over to the Server from the GUI as I can echo it on the server side, but it is not being read and parsed properly as the stdin is. Nothing is being sent back to the client. I have tried flushing, using different streams and adding line separators all over the place to no avail. There is also a Protocol class that handles the data on the Server side.
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
System.out.println("Waiting for client...");
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye.")) {
break;
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
.
public class KnockKnockClient {
public static PrintWriter out = null;
public static String sendAnswer;
public static void Client() {
//JButton Action Listener
saveAnswer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel b = group.getSelection();
if (b.getActionCommand() == "A") { sendAnswer = radioA.getText(); }
String data = "รท" + sendAnswer;
out.println(data);
}
});
}
public static void main(String[] args) throws IOException {
KnockKnockClient.Client();
Socket kkSocket = null;
//PrintWriter out = null;
BufferedReader in = null;
try {
kkSocket = new Socket("localhost", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer, fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
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 have a problem when the client send data to the server. When I send data from the server to the client everything is okay. I received this message: "client receive: message" but then when I send "client's message", my server do not receive it.
import java.io.IOException;
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
outputLine = "message";
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
System.out.println("server receive: " + inputLine);
outputLine = "second message";
out.println(outputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
this.main.getContentPane().remove(homePanel);
String name = this.name.getText();
String result;
try {
connectionToServer();
if ((result = in.readLine()) != null) {
System.out.println("client receive: " + result);
out.println("client's message");
}
} catch(IOException err) {
System.out.println("error");
}
}
}
public void connectionToServer() throws IOException {
try {
this.socket = new Socket("localhost", 4444);
this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
this.out = new PrintWriter(this.socket.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
}
}
your actionPerformed method just link the server and do nothing.
The server closed after send a message.
watch: while ((inputLine = in.readLine()) != null)
if client don't send any message,code will break,then you closed the server.