I was given the below code by my teacher for a class. I ran it one or twice and it worked fine. However I suddenly cannot get it to run from the command prompt on Windows 8 anymore. No matter what port I specify it just prints "Opening port..." and never continues. No exception is ever thrown. I have disabled my firewall and antivirus and it does not seem to work. I have added a print statement as the first line of the try catch block and it will print but it just will not create the new Socket. I am sure it is something in my Windows settings but I am unsure as to what or how to resolve it.
// Server program
// File name: "TCPServer.java"
import java.io.*;
import java.net.*;
public class TCPServer
{
private static ServerSocket servSock;
public static void main(String[] args)
{
System.out.println("Opening port...\n");
try{
// Create a server object
servSock = new ServerSocket(Integer.parseInt(args[0]));
}
catch(IOException e){
System.out.println("Unable to attach to port!");
System.exit(1);
}
do
{
run();
}while (true);
}
private static void run()
{
Socket link = null;
try{
// Put the server into a waiting state
link = servSock.accept();
// Set up input and output streams for socket
BufferedReader in = new BufferedReader(new InputStreamReader(link.getInputStream()));
PrintWriter out = new PrintWriter(link.getOutputStream(),true);
// print local host name
String host = InetAddress.getLocalHost().getHostName();
System.out.println("Client has estabished a connection to " + host);
// Receive and process the incoming data
int numMessages = 0;
String message = in.readLine();
while (!message.equals("DONE"))
{
System.out.println(message);
numMessages ++;
message = in.readLine();
}
// Send a report back and close the connection
out.println("Server received " + numMessages + " messages");
}
catch(IOException e){
e.printStackTrace();
}
finally{
try{
System.out.println("!!!!! Closing connection... !!!!!\n" + "!!! Waiting for the next connection... !!!");
link.close();
}
catch(IOException e){
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
}
This code works fine. The problem is the code for the client. The answer to your problem is already written in a comment in your code.
// Put the server into a waiting state
link = servSock.accept();
The server goes into a waiting state until it gets a connection. The client is the one that would be getting the error since it did not connect. If the client was working correctly the code would continue and you would get the additional output.
Related
I'm new to java socket programming, I'm making a client server program. the server is multithreaded.
when the client connection with server is open. the server sends a text block to the client like this:
connection is open with the server....
Welcome Please Chose one of the following Operations
Insert, Read, Update, Delete
Type Exit to terminate connection.
when I type read or exit or any of the operations it works fine and the server responds.
but the problem happens when I chose an operation i.e insert --> when the server responds and asks me for input and I wanna insert a value, the program keeps taking input infinitely for endless lines I don't know where the problem and how it happens.
it's the same code, the client sends the input as one line when choosing operation but when I chose insert operation and the server is expecting a value it takes it as infinite endless lines.
Client class
public class Client1 {
public static void main(String[] args) throws IOException {
Socket socket=null;
try {
System.out.println("sending connection request to host 127.0.0.1 at port 2000");
socket = new Socket("127.0.0.1", 2000);
System.out.println("connection is open with the server....");
Scanner scn = new Scanner(System.in);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
while (true) {
System.out.println(dis.readUTF());
String tosend = scn.nextLine();
dos.writeUTF(tosend);
// If client sends exit,close this connection
// and then break from the while loop
if (tosend.equals("Exit")) {
System.out.println("Closing this connection : " + socket);
socket.close();
System.out.println("Connection closed");
break;
}
String received = dis.readUTF();
System.out.println(received);
}
// closing resources
scn.close();
dis.close();
dos.close();
}
catch (Exception e ){
System.out.println(e);
} finally {
try {
if (socket != null) socket.close();
} catch (Exception e){
System.out.println(e);
}
}
}
Server Class
public class ServerThread extends Thread{
Socket socket ;
DataInputStream dis;
DataOutputStream dos;
ServerThread(Socket socket,DataInputStream dis,DataOutputStream dos ){
this.socket = socket;
this.dis=dis;
this.dos=dos;
}
#Override
public void run(){
String received;
String toreturn;
String welcomeText = """
Welcome Please Chose one of the following Operations
Insert, Read, Update, Delete
Type Exit to terminate connection.""";
while (true){
try {
// Ask user what he wants
dos.writeUTF(welcomeText);
// receive the answer from client
received = dis.readUTF();
if(received.equals("Exit"))
{
System.out.println("Client " + this.socket + " sends exit...");
System.out.println("Closing this connection.");
this.socket.close();
System.out.println("Connection closed");
break;
}
// write on output stream based on the
// answer from the client
switch (received) {
// the problem starts here if I chose insert and wanna print what the user typed, it takes
//input infinitely from the user
case "Insert":
toreturn = "Inserting new info...";
dos.writeUTF(toreturn);
String out = dis.readUTF();
dos.writeUTF("Accepted");
dos.writeUTF(out);
break;
case "Read":
toreturn = "Reading User Info...";
dos.writeUTF(toreturn);
break;
case "Update":
toreturn = "Updating User Info...";
dos.writeUTF(toreturn);
break;
case "Delete":
toreturn = "Deleting User Info";
dos.writeUTF(toreturn);
break;
default:
dos.writeUTF("Unknown User");
break;
}
} catch ( IOException e) {
e.printStackTrace();
}
}
try
{
// closing resources
this.dis.close();
this.dos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
I don't know how this loop happens especially since the server accepts input correctly when choosing operations but when insert operation is chosen it just takes input infinitely, can anyone help please, i cant implement any operation if this problem persists.
I think its your Client, in the while loop try to remove the second read from server, it's because you once read all what server sents, and when the loop starts again wants to read from server but there is nothing to read and becomes idle.
I am attempting a client/server type chat box (using GUI's). I won't get into details of the multi-threading I used in the program since I believe it is not part of the problem (I hope not) and it will be good amount of code to post. Anyways, for both my client and my server I create a socket, and some other stream classes within a try block, and some reason the sockets close after the catch blocks. PS I do NOT call socket.close() method anywhere that could end if early
Server, this is ran into a constructor of one of my class. It breaks down into, my main has the actually server stuff on a different thread, (like my previous post) it is a fix so that the gui can load and run the server stuff without one waiting on the other. Anyways, without all that detail, here is my code
public ChatAppProtocol(Socket sock)
{
super("ChatAppServer");
// this also has a clas var of Socket
this.sock = sock;
try (
PrintWriter output = new PrintWriter(this.sock.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(this.sock.getInputStream())) ;
)
{
// first stream of a string is the username loging in from client
String name = input.readLine();
// this returns false, so its not closed
System.out.println("closed?: " + this.sock.isClosed());
}
catch (IOException e)
{
e.printStackTrace();
}
// PROBLEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// closed after the catch blocks before methods even ends
// p.s. i also plan on using the socket in another method but can't since it closes
System.out.println("closed?: " +this.sock.isClosed());
}
now my client
#FXML
private void login()
{
this.name = this.username.getText().trim();
this.portnum = Integer.parseInt(this.port.getText());
this.name = this.username.getText().trim();
this.ipaddr = this.ip.getText().trim();
try (t
Socket socket = new Socket(this.ipaddr, this.portnum);
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
)
{
this.sock = socket;
output.println(this.name);
// this returns false, not closed
System.out.println("closed?: " +this.sock.isClosed());
}
catch (UnknownHostException e)
{
System.err.println("Problem at ip: " + this.ipaddr);
System.exit(1);
}
// PROBLEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// returns true here, closes before methods end and i cant reuse it
System.out.println("IS IT CLOSED!!!!!! " + this.sock.isClosed());
}
}
so, any reason why both this different class, different files, different project sockets close after try-catch blocks? Can't find answer online, and been on it for a while and I am stuck. I found out about this problem after seeing this on the server side console
java.net.SocketException: Socket is closed
at java.net.Socket.getOutputStream(Socket.java:943)
at chatappserver.ChatAppProtocol.run(ChatAppProtocol.java:62)
Because you're creating socket with the brackets of the try block, it is automatically closed upon exiting the block. Instead, try creating it inside the block itself and it shouldn't be closed:
try {
this.sock = new Socket(this.ipaddr, this.portnum);
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
output.println(this.name);
} catch (UnknownHostException e) {
System.err.println("Problem at ip: " + this.ipaddr);
System.exit(1);
}
// this.sock should still be open at this point.
Have a read of the Java tutorial on try-with-resources for more information on why you're getting your current behaviour.
You are using try-with-resources, which is roughly an equivalent of:
try
{
this.sock = new Socket(this.ipaddr, this.portnum));
output.println(this.name);
// this returns false, not closed
System.out.println("closed?: " +this.sock.isClosed());
}
catch (UnknownHostException e)
{
System.err.println("Problem at ip: " + this.ipaddr);
System.exit(1);
} finally {
if (this.sock != null)
this.sock.close();
}
Just initialize the socket outside the resources clause of try (...) and it won't get closed
I'm working on a java server-client based file transfer over socket project, I'll sum up the project shortly, I have text files related to server and client, server related text contains which ports are going to be opened and client text contains the IP and port to be connected on(server side is like 4444 and client side is like 4444 localhost) The file transfer on a single client is running pretty ok, now I'm working on second client connection and transfer, what I'm trying to do is; when a second client is run, it will read the first line of the text file (which is already in use by the first client), I thought a recursion will solve the problem but seems I couldn't figure out what I've done wrong, below are the code snippet from client side
boolean connected = false;
private void connection() {
while (!connected) {
try {
FileReader fr = new FileReader("c_input.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
String delims = "[ ]";
String[] elements = new String[8];
elements = line.split(delims);
serverPort = Integer.parseInt(elements[portIndex]);
hostIP = elements[ipIndex];
clientSocket = new Socket(hostIP, serverPort);
is = clientSocket.getInputStream();
if (is != null) {
connected = true;
System.out.println("connected to " + hostIP + " from port "
+ serverPort);
br.close();
fr.close();
} else {
System.out.println("The port " + serverPort
+ " is occupied, now trying another port.");
portIndex = portIndex + 2;
ipIndex = ipIndex + 2;
connection();
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
}
I used recursion there, because if a port is bound by another client it has to read another line from text file and split and retry connection with the new line's inputs.(in terms short the whole method will run again) But when it comes to running, the first client connects and when second one tries to connect from same port with client1 the code still gets in if loop instead of getting in else block (I get the message from the if check's println on the console and by the way is in the if check stands for InputStream) which means there is a stream coming from server, is this normal? if so how can I achieve the whole thing connection method does all over again if the port is bound by another client?
I'm writing a simple client-server application using TCP Sockets . It works with the multi-threading principle to allow for several client connections to the same server.
I'm having some trouble figuring out some of the errors I get with the sockets, i'm fairly new in this environment as you will probably tell.
I'll show you the code I have, and the output i get from it, but basically the problem lies in the very connecting of the clients to the server, and I ran through all the code but still can't find what's wrong with it.
Server:
public static ArrayList<String> userList = new ArrayList<String>();
public static int index;
public static String date;
public static void main(String args[]) throws Exception {//inicio main
ServerSocket server = new ServerSocket(6500); //Create socket on port 6500
System.out.println ("Server started on port 6500");
while (true){ //Waiting for clients
System.out.println("Server waiting for client connections..");
Socket socket = null;
BufferedReader reader = new BufferedReader(new FileReader("C:\\UNIV\\Redes\\workspace\\Copy of Ex_4.3_Teste\\lists\\blacklist.txt"));
String line = null;
socket = server.accept();
// Blacklist verification
while ((line = reader.readLine()) != null) {
if (line.equals(socket.getInetAddress().toString())) {
System.out.println("IP Blacklisted: " + socket.getInetAddress().toString());
System.out.println("Closing connection to " + socket.getInetAddress().toString());
PrintStream checkBlack = new PrintStream(socket.getOutputStream(),true);
checkBlack.println("***BLACKLISTED***");
reader.close();
checkBlack.close();
socket.close();
break;
}
}//End of Blacklist Verification
//Sending feedback in case of approved client
try {
PrintStream checkBlack = new PrintStream(socket.getOutputStream(),true);
checkBlack.println("***NBLACKLISTED***");
checkBlack.close();
} catch (SocketException e) {
}
userList.add(socket.getInetAddress().toString()); //Add connected user's IP to USERLIST
System.out.println("New connection..");
System.out.println("Size of UserList: " + userList.size());
Thread t = new Thread(new EchoClientThread(socket));
t.start(); //Starting Client Thread
}//End of Waiting for Clients
}//End of Main
public static class EchoClientThread implements Runnable{
private Socket s;
public EchoClientThread(Socket socket) {
this.s = socket;
}
public void run() {
String threadName = Thread.currentThread().getName(); //Thread Name
String stringClient = s.getInetAddress().toString(); //Client IP
System.out.println("Connected to " + stringClient);
try{
BufferedReader input = new BufferedReader(
new InputStreamReader(s.getInputStream()));
PrintStream output = new PrintStream(
s.getOutputStream(),true);
String line;
while ((line = input.readLine()) !=null) { //Input Cycle
System.out.println (stringClient+": "+threadName+": "+line); //Print command from client
if (line.equalsIgnoreCase("9")){ //Exit
break;
}
else if (line.equalsIgnoreCase("1")){ //Send List of Online Users
System.out.println("Option 1: Sending list of online users to " + stringClient);
output.println(" ");
output.println("List of Online Users:");
output.println(" ");
for(int i=0;i<userList.size();i++){
output.println(userList.get(i));
}
}
else if (line.equalsIgnoreCase("2")) { //Send message to a single user
System.out.println("Nothing here yet..");
}
else if (line.equalsIgnoreCase("3")) { //Send message to all the online users
System.out.println("Nothing here yet..");
}
else if (line.equalsIgnoreCase("4")){ //Send User Blacklist
System.out.println("Option 4: Sending user blacklist to " + stringClient);
BufferedReader reader = new BufferedReader(new FileReader("C:\\UNIV\\Redes\\workspace\\Copy of Ex_4.3_Teste\\lists\\blacklist.txt"));
String lineRead = null;
output.println(" ");
output.println("User Blacklist:");
output.println(" ");
while ((lineRead = reader.readLine()) != null) {
output.println(lineRead);
}
reader.close();
}
else{
output.println("Unknown command.");
}
output.println("***CLOSE***"); //Closes client's input cycle
output.println("***NBLACKLISTED***"); //Sending feedback in case of approved client
}//Input Cycle End
output.println("See you later!");
input.close(); //Closes inputStream
output.close(); //Closes outputStream
s.close(); //Closes Socket
}
catch (Exception e){
System.err.println("Server Side Error!");
System.out.println(e);
}
userList.remove(s.getInetAddress().toString());
System.out.println("Client "+ stringClient+" was disconnected!");
}//End of run()
}//End of EchoClientThread
}//End of EchoServerThread
Client:
public static void main(String args[]) throws Exception {
if (args.length !=1){
System.err.println ("usage: java EchoClient2 <host>");
System.exit(1);
}
String host = args[0];
int port = 6500;
String cmd, line;
Socket socket = new Socket(host,port);
BufferedReader input = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintStream output = new PrintStream(socket.getOutputStream(),true);
while( true ) {//Input cycle
Scanner scan = new Scanner (System.in);
if (input.readLine().equals("***BLACKLISTED***")) {
System.out.println("IP is Blacklisted");
break;
}
System.out.println(" ");
System.out.println("CLIENT MENU");
System.out.println(" ");
System.out.println("1 - List on-line users");
System.out.println("2 - Send message to a single user");
System.out.println("3 - Send message to all on-line users");
System.out.println("4 - List Blacklisted Users");
System.out.println("9 - Exit");
System.out.println(" ");
System.out.print(host+":"+port+"#>"); //Command prompt
cmd = scan.nextLine(); //Scanning command to send to the server
output.println(cmd); //Sending command to the server
if ( cmd.equalsIgnoreCase("9")){
System.out.println("Exiting..");
break;
}
try {
while (!(line = input.readLine()).equals("***CLOSE***")) { //Input Cycle
System.out.println (line); //Prints server answer
}
} catch (Exception e) {
System.err.println("Client Side Error!");
System.out.println(e);
break;
}
}//End of Cycle
System.out.println("Connection Terminated");
input.close(); //Closes inputStream
output.close(); //Closes outputStream
socket.close(); //Closes Socket
}
}
So the server starts fine with the following output:
Server started on port 6500
Server waiting for client connections..
But as soon as I try to connect with the client, this happens:
Server Side:
Server started on port 6500
Server waiting for client connections..
New connection..
Size of UserList: 1
Server waiting for client connections..
Connected to /127.0.0.1
java.net.SocketException: Socket is closed
Server Side Error!
Client /127.0.0.1 was disconnected!
On the client side, though, it still shows the input menu, and the command prompt, like so:
CLIENT MENU
1 - List on-line users
2 - Send message to a single user
3 - Send message to all on-line users
4 - List Blacklisted Users
9 - Exit
127.0.0.1:6500#>
And when I input something on the Client Side prompt, i get:
127.0.0.1:6500#>1
Client Side Error!
java.net.SocketException: Software caused connection abort: recv failed
Connection Terminated
I know what the errors mean, Socket is closed is pretty much self-explanatory, but i just can't find wheres the code problem that makes the socket close.
Any help is much appreciated.
You have your blacklist mechanism not quite right.
When you close a stream associated with the socket it will close the socket as well.
So the server is closing any socket that it gets and then hands it on to a thread,
which tries to use the socket and fails.
// Blacklist verification
while ((line = reader.readLine()) != null) {
// blah blah blah
}//End of Blacklist Verification
//Sending feedback in case of approved client
try {
PrintStream checkBlack = new PrintStream(socket.getOutputStream(),true);
checkBlack.println("***NBLACKLISTED***");
checkBlack.close(); // <== why are you closing the stream?
} catch (SocketException e) {
}
try this instead
// Blacklist verification
while ((line = reader.readLine()) != null) {
// blah blah blah
}//End of Blacklist Verification
//Sending feedback in case of approved client
try {
socket.getOutputStream().write("***NBLACKLISTED***\n".getBytes());
} catch (SocketException e) {
e.printStackTrace();
}
A debugger is your friend.
In the code below, what determines what will be sent back to the client (the PHP page). I am trying to alter this so that it sends a variable back to the PHP page with an error message that is defined based on actions made in my java code.
Edit: To answer some questions, what I am trying to do is this.
Send a string to the java script with a socket and convert it to a variable to be used in the java script. It will run through some if statements and I need to set the error statements to a variable lets say "reply". I need to send "reply" then back to the PHP file.
public class MyJavaServer {
public static void main(String[] args) {
int port = 20222;
ServerSocket listenSock = null; //the listening server socket
Socket sock = null; //the socket that will actually be used for communication
try {
listenSock = new ServerSocket(port);
while (true) { //we want the server to run till the end of times
sock = listenSock.accept(); //will block until connection recieved
BufferedReader br =
new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw =
new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
String line = "";
while ((line = br.readLine()) != null) {
bw.write("PHP said: " + line + "\n");
bw.flush();
}
//Closing streams and the current socket (not the listening socket!)
bw.close();
br.close();
sock.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
If I get your question right, the line where the answer gets sent to the peer is
bw.write("PHP said: " + line + "\n");
which writes the given string to bw.