This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JAVA SOCKET PROGRAMMING

 
Adi Peyyala
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried writing a client-server java program with the on my machine. The program seem to compile perfectly with the exception that when I run the programs the client exits without giving any message. Could someone help me out.

Thanks.

Server:

import java.io.*;
import java.net.*;

public class Server {

public static void main(String[] args) {

ServerSocket serverSocket = null;
String line;
BufferedReader is;
PrintStream os;
Socket clientSocket = null;

try {
serverSocket = new ServerSocket(8082);
}

catch(IOException e) {
System.out.println(e);
}

try {
clientSocket = serverSocket.accept();
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());

while(true) {
line = is.readLine();
os.println(line);
}
}


catch(IOException e) {
System.out.println(e);
}
}
}


Client:

import java.io.*;
import java.net.*;

public class Client {

public static void main(String[] args) {

Socket clientSocket = null;
DataOutputStream os = null;
BufferedReader is = null;

if(clientSocket != null && os != null && is!= null) {

try {
try {

clientSocket = new Socket("localhost", 8082);
os = new DataOutputStream(clientSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch(UnknownHostException e) {
System.err.println("Unknown host name");
} catch(IOException e) {
System.err.println("I/O Connection failure");
}

os.writeBytes("HELLO\n");

String responseLine;
while((responseLine = is.readLine()) != null) {

System.out.println("Server:" + responseLine);
}

os.close();
is.close();
clientSocket.close();

} catch(UnknownHostException e) {
System.err.println("Unknown host name");
} catch(IOException e) {
System.err.println("I/O Connection failure");
}
}
}
}
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


If your socket, stream or reader are not initialised you don't initialise them but exit the appliction.
As they're declared uninitialised on the line directly prior to your conditional they'll always be uninitialised in the conditional and your application will never do much of anything at all except wonder why it's ready so quickly and terminate in utter confusion.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic