import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPClient2 {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.out.println("Incorrect number of args, exiting...");
System.exit(0);
}
String host_address = args[0];
String resource = args[1];
Socket socket =null;
PrintWriter out = null;
BufferedReader in = null;
int port=80;
try {
socket = new Socket(host_address,port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (UnknownHostException e) {
System.out.println("Unknown host");
System.exit(-1);
}
catch (IOException e) {
System.out.println("No I/O");
System.exit(-1);
}
try {
String request_line = "GET " + resource + " HTTP/1.1";
String host_header = "Host: " + host_address;
out.println(request_line);
out.println(host_header);
out.println(); // blank line = end of request header
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
}
catch (IOException e) {
System.out.println("Error during communication");
System.exit(-1);
}try {
socket.close();
}
catch (IOException e) {
System.out.println("Cannot close the socket");
System.exit(-1);
}
}
}
hello ,i have just started learning java network programming, i tried to send a http request and i was expecting getting its information but it returns "No I/O" all the time but it connects to server . Can any one tell where do i make mistake ?
Related
This is my simple server program with java's ServerSocket class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServerSocketTest {
public static void main(String[] args) {
while (true)
{
try {
if (args.length != 1) {
System.err.println("Usage: java StartServer <port>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for client...on " + port);
Socket client = server.accept();
System.out.println("Client from /" + client.getInetAddress() + " connected.");
BufferedReader rdr = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
Writer out = new OutputStreamWriter(client.getOutputStream());
String nameClient = rdr.readLine();
System.out.println("Client " + nameClient + " wants to start a game.");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
I am trying to run config the server
but it keeps on saying this "Usage: java StartServer ".
I want to know how can I config the port when the port is args[0].
This is in Eclipse, by the way.
If it keeps saying "Usage: java StartServer" it therefore means this code
System.err.println("Usage: java StartServer <port>");
Is always been executed which means the condition
args.length != 1
Is always true. This could mean args.length = 0 or args.length > 1
Did you make eclipse pass the port number when running your application? That is did you configure any command line arguments to be used? I'm not a user eclipse so I can't help you here. See if this tutorial is helpful http://www.concretepage.com/ide/eclipse/how-to-pass-command-line-arguments-to-java-program-in-eclipse or you could try to find some other tutorial.
Also make sure you didn't pass too many arguments than is required because that will also make the condition to return true. Just pass as many arguments to make the condition args.length != 1 fail which is having 1 argument.
You can also see this question with help configuring command line arguments in eclipse.
This is my practice for you.
Copy and complete your code.
Select menu clicking right button of your mouse, Run > Run Configurations
Select Arguments tab and type a port number whatever you want your server to wait for client connection then, run it.
Test it with your client socket program.
This is my practice using client socket programming.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SimpleClientSocketTest {
public static void main(String[] args) {
BufferedReader rdr = null;
Socket sock = null;
PrintWriter out = null;
try{
sock = new Socket("localhost", 9999);
rdr = new BufferedReader(new InputStreamReader(sock.getInputStream(), "UTF-8"));
out = new PrintWriter(sock.getOutputStream(), true);
String toServer = "hello...";
out.println(toServer + "i wants to start a game.");
String fromServer = rdr.readLine();
System.out.println("server: " + fromServer);
if(fromServer == null) System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
finally
{
try {
rdr.close();
out.flush();
out.close();
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Send a message to the server first,
out.println(toServer + "i wants to start a game.");
then, receive from the server.
String fromServer = rdr.readLine();
System.out.println("server: " + fromServer);
There is one more thing to tell you about your server program.
This is a customized version of yours.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServerSocketTest {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java StartServer <port>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
ServerSocket server = null;
try {
server = new ServerSocket(port);
} catch (IOException e2) {
e2.printStackTrace();
}
while (true) {
BufferedReader rdr = null;
PrintWriter out = null;
int clientConnectionCnt = 0;
try {
System.out.println("1Waiting for client...on " + port);
Socket client = server.accept();
if(client.isConnected())
{
System.out.println("Client from /" + client.getInetAddress() + " connected.");
String nameClient = null;
try {
rdr = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
out = new PrintWriter(client.getOutputStream(), true);
System.out.println("clientConnectionCnt....." + clientConnectionCnt++);
nameClient = rdr.readLine();
out.println("Yes, You can");
if(nameClient == null) break;
System.out.println("Client: " + nameClient);
} catch (IOException e) {
e.printStackTrace();
break;
} finally {
out.flush();
rdr.close();
out.close();
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
try {
server.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
First, you should create a server socket outside of while statement not in a while.
try {
server = new ServerSocket(port);
} catch (IOException e2) {
e2.printStackTrace();
}
Just wait in a while statement util client socket accepting.
while (true) {
.... skip ...
System.out.println("1Waiting for client...on " + port);
Socket client = server.accept();
Then, create in/out stream of client socket.
rdr = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
out = new PrintWriter(client.getOutputStream(), true);
Finally, read and write a message with the socket's stream.
nameClient = rdr.readLine();
out.println("Yes, You can");
Regards, Rach.
I have used both a reader object and a scanner but while this client is connected to a simple socket server and they are both running, I cannot take an input from the user in the console and pass it to the server. pressing enter simply skips a line, scanner.nextLine() seems to capture nothing or something is going wrong when passing a variable to the output streamer.
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
Socket socket = null;
DataOutputStream outputStream = null;
BufferedReader reader = null;
Scanner scan = new Scanner(System.in);
String message;
String host = "macbook";
int port = 9999;
//attempts to connect to given host and port
try {
socket = new Socket(host, port);
outputStream = new DataOutputStream(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + host +".");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + host+".");
e.printStackTrace();
}
// if everything has been initialized then write some data
if (socket != null && outputStream != null && reader != null) {
try {
message=scan.nextLine();
outputStream.writeBytes(message);
String responseLine;
while ((responseLine = reader.readLine()) != null) {
System.out.println("Server: " + responseLine);
if (responseLine.indexOf("Ok") != -1) {
break;
}
}
//closes client once communication with server has ended
outputStream.close();
reader.close();
socket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}
I'm creating an "echo" server that upon receiving a message simply sends it back. I have managed to get multi-client working, but I want to make some kind of disconnect detection. I tried to get it working through sending a single character from the server, then replying with another character from the client. I couldn't get this to work, though.
How would you suggest I go about disconnect detection?
MessageServer.java
import java.net.*;
import java.io.*;
public class MessageServer {
static int clientCount = 0;
public static void main(String[] args) throws IOException {
try(ServerSocket servSocket = new ServerSocket(16384)){
while(true){
Socket socket = servSocket.accept();
addClient();
new ServerThread(socket, clientCount).start();
}
} catch(IOException e) {
System.out.println("Exception caught when trying to listen on port 16384 or listening for a connection");
System.out.println(e.getMessage());
}
}
public static void addClient(){
clientCount++;
}
}
ServerThread.java
import java.net.*;
import java.io.*;
public class ServerThread extends Thread {
private Socket cltSocket;
private BufferedReader in;
private PrintWriter out;
private int num;
public ServerThread(Socket clientSocket, int count) {
cltSocket = clientSocket;
num = count;
}
public void run() {
String input;
try {
out = new PrintWriter(cltSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(cltSocket.getInputStream()));
System.out.println("Client " + num + " connected!");
while(cltSocket.isConnected() && !cltSocket.isClosed()){
if(in.ready()){
input = in.readLine();
if(input != null && !(input.equalsIgnoreCase("exit"))){
System.out.print("New input: ");
System.out.println(input);
out.println(input);
out.flush();
} else if(input.equalsIgnoreCase("exit")){
disconnect();
}
}
}
} catch(SocketException e) {
disconnect();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
public void disconnect(){
System.out.println("Client " + num + " disconnected!");
out.close();
try {
in.close();
cltSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
MessageClient.java
import java.net.*;
import java.io.*;
public class MessageClient {
public static void main(String[] args) {
if(args.length != 2) {
System.out.println("Invalid parameters! Format as: (hostname) (port)");
System.exit(1);
}
String hostname = args[0];
int port = Integer.parseInt(args[1]);
try {
Socket socket = new Socket(hostname, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Connected!");
while(socket.isConnected() && !socket.isClosed()){
String output;
if(con.ready()) {
output = con.readLine();
out.println(output);
if(output.equalsIgnoreCase("exit")) {
socket.close();
}
}
if(in.ready()){
String li = in.readLine();
if(li != null) {
System.out.println(li);
}
}
}
System.out.println("Disconnected!");
con.close();
out.close();
in.close();
System.exit(0);
} catch(SocketException e) {
System.err.println("Socket error:" + e);
} catch(UnknownHostException e) {
System.err.println("Invalid host");
} catch(IOException e) {
System.err.println("IO Error: " + e);
}
}
}
There is a way to do that:
if you read the BufferedReader by calling BufferedReader.getLine() and the other side socket is gone, then you get an SocketException... that is a way to check a lost connection
what it do..
1. an iterative dictionary server that is listening clients requests..
2. connection will be established..
3. server will accept input string from client..
4. then server will search meaning of string from a file..
5. then server will return meaning to the client..
problem is with the while loop of server.. if it finds word it will send that word's meaning to client..fine.. but if word is not found... this
if(d.equals(null)){
input="No knowledge";
out.println(input);
out.flush();
}
doesn't execute... client says null and server says null exception...
what i am doing wrong here... i'm not getting it...!!
i have tried to changed this code...
client-server online dictionary program in java
client:
import java.io.;
import java.net.;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class DCC1 {
public static void main(String[] args) throws IOException {
final int PORT = 8888;
Socket s = null;
PrintWriter out = null;
try {
s = new Socket("localhost", PORT);
out = new PrintWriter(s.getOutputStream()); // Output stream to the server
}
catch (UnknownHostException ex) {
System.err.println("Unknown host: " + PORT);
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
catch (IOException ex) {
System.err.println("Cannot get I/O for " + PORT);
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
Scanner user = new Scanner(System.in); // Scanning for user input
System.out.print("Enter String: ");
String input;
input = user.next(); // Hold the input from the user
out.println(input); // Send it to the server
out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream( )));
System.out.println(br.readLine());
out.close();
s.close();
}
}
server:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class DSC1
{
public static void main(String[] args) throws IOException
{
final int PORT = 8888;
final String FILE_NAME = "dictionary.dat";
ServerSocket server = new ServerSocket(PORT);
Socket s = null;
PrintWriter out = null;
Scanner in = null;
FileInputStream fin = null;
ObjectInputStream oin = null;
while (true)
{
try
{
s = server.accept();
}
catch (IOException ex)
{
System.err.println("Accept failed");
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
System.out.println("Accepted connection from client");
try
{
in = new Scanner(s.getInputStream()); // Input stream from the client
out = new PrintWriter(s.getOutputStream()); // Output stream to the client
String temp = in.next(); // String holding the word sent from the client
System.out.println("From the client " + temp);
String input = null;
fin = new FileInputStream(FILE_NAME);// The dictionary file
oin = new ObjectInputStream(fin);
dictionary d = (dictionary)oin.readObject();
while(d!= null)
{
System.out.println("in loop...");
if(d.name.equals(temp)){
input=d.meaning;
d.printDic();
out.println(input);
out.flush();
break;
}
d = (dictionary)oin.readObject();
if(d.equals(null))
{
input="No knowledge";
out.println(input);
out.flush();
}
}
}
catch (ClassNotFoundException|IOException ex)
{
System.err.println("Exception: " + ex.getMessage());
System.out.println("Closing connection with client");
in.close();
System.exit(1);
}
in.close();
}
}
}
Don't use d.equals(null). If you want to check if d is null, just do if (d==null).
Why? There's no way this can return true, so probably that's the reason why this code never executes and you don't get what you expect.
I'm trying to implement a server-client socket program in Java that can support multiple clients, but my class that performs the multithreading always crashes whenever my client connects to my server.
import java.io.*;
import java.net.*;
public class ClientWorker extends Thread{
Socket cwsocket=null;
public ClientWorker(Socket cwsocket){
super("ClientWorker");
cwsocket=cwsocket;
}
public void run(){
try {
PrintWriter out = new PrintWriter(cwsocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(cwsocket.getInputStream()));
String serverinput, serveroutput="";
out.println(serveroutput);
while ((serverinput = in.readLine()) != null) {
out.println(serveroutput);
if (serveroutput.equals("Terminate"))
break;
}
out.close();
in.close();
cwsocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Whenever I create a PrintWriter object, a NullPointerException exception is thrown, and I'm not sure why it continues to happen. Below are my server and client classes. What am I doing wrong?
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[]args)throws IOException{
ServerSocket serversocket=null;
final int PORT_NUM=4444;
boolean flag=true;
try{
System.out.println("Listening for connection");
serversocket=new ServerSocket(PORT_NUM);
}catch(IOException e){
System.out.println("Could not listen to port: "+PORT_NUM);
System.exit(-1);
}
while(flag){
new ClientWorker(serversocket.accept()).start();
}
System.out.println("Terminating server...");
serversocket.close();
}
}
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args){
Socket socket=null;
PrintWriter out=null;
BufferedReader in=null;
BufferedReader userInputStream=null;
String IP="127.0.0.1";
try{
socket = new Socket(IP, 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host:" + IP);
System.exit(1);
} catch (IOException e) {
System.out.println("Cannot connect to server...");
System.exit(1);
}
String userInput, fromServer;
try{
userInputStream = new BufferedReader(new InputStreamReader(System.in));
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Terminate"))
break;
userInput = userInputStream.readLine();
if (userInput != null) {
System.out.println("> " + userInput);
out.println(userInput);
}
}
}catch(IOException e){
System.out.println("Bad I/O");
System.exit(1);
}
try{
out.close();
in.close();
userInputStream.close();
socket.close();
System.out.println("Terminating client...");
}catch(IOException e){
System.out.println("Bad I/O");
System.exit(1);
}catch(Exception e){
System.out.println("Bad I/O");
System.exit(1);
}
}
}
In
public ClientWorker(Socket cwsocket){
super("ClientWorker");
cwsocket=cwsocket;
}
You need to do
this.cwsocket=cwsocket;
Or rename the parameter so it doesn't shadow the member of the same name.