Client Side
I am using this on my pc. I am using MAMP and it is installed and everything seems fine but.
package com.data.jdbc;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class ClientDemo {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("127.0.0.1", 8888);
Scanner is = new Scanner(s.getInputStream()); //receive data from server
System.out.println("Enter the string");
Scanner scan = new Scanner(System.in);
String name = scan.next();
PrintStream p = new PrintStream(s.getOutputStream());
p.println(name);
String temp=is.next();
System.out.println(temp);
// TODO Auto-generated method stub
}
}
Server Side
I am using this on my pc , MAMP is installed and everything seems fine but.
package com.data.jdbc;
import java.io.IOException;
import java.io.PrintStream;
import java.net.*;
import java.util.Scanner;
public class ServerDemo {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket sc1 = new ServerSocket(8888);
Socket s11 = sc1.accept();
Scanner scan1 = new Scanner(s11.getInputStream());
String name1 = scan1.next();
String temp1= name1 + "Poudel";
PrintStream p1 = new PrintStream(s11.getOutputStream());
p1.println(temp1);
}
}
Error
I am getting a bind error as below:
Exception in thread "main" java.net.BindException: Address already in use (Bind failed)
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at com.data.jdbc.ServerDemo.main(ServerDemo.java:18)
What might be the cause of above problem?
Related
what's wrong in this code? I'm trying to make compiler accept my keyboard input; but compilation is not ending while it's also not throwing any error or warning. I'm using Eclipse 4.14 for Mac OS X. Can anyone suggest.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestInputStream {
public static void main(String args[]) throws IOException {
InputStreamReader Obj = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(Obj);
int a = Integer.parseInt(br.readLine());
System.out.println("Please enter your choice");
System.out.println("You have entered " + a);
}
}
I am developing a simple 2D multiplayer game in Java, following the Client-Server model. The functionality in terms of the socket programming is simple:
A Client sends the Server their character data (x position, y position, health points, etc.)
The Server registers the updated character data in a table which is storing all the different Clients' character data
The Server sends back the table to the Client so that they can render the other characters
I am running into a weird issue that I would like help understanding so I can move forward with the project. Here is the code I'm running right now.
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Set;
import java.util.Vector;
import java.util.HashSet;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server
{
private static Vector<Integer> IDs = new Vector<>();
public static void main(String[] args) throws Exception
{
ExecutorService pool = Executors.newFixedThreadPool(32);
try (ServerSocket listener = new ServerSocket(40000))
{
System.out.println("The server is up.");
while (true)
{
pool.execute(new Player(listener.accept()));
}
}
}
private static class Player implements Runnable
{
private Socket socket;
private Scanner input;
private PrintWriter output;
private int ID;
public Player(Socket socket)
{
this.socket = socket;
this.ID = IDs.size() + 1;
IDs.add(ID);
}
public void run()
{
try
{
input = new Scanner(socket.getInputStream());
output = new PrintWriter(socket.getOutputStream(), true);
while(input.hasNextLine())
{
String result = "";
for(int i = 0; i < IDs.size(); i++)
{
result += (IDs.get(i) + " ");
}
output.println(result);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception {
try (Socket socket = new Socket("127.0.0.1", 40000)) {
Scanner scanner = new Scanner(System.in);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
System.out.println(in.nextLine());
}
in.close();
scanner.close();
}
}
}
What I want to happen is: every time a Client sends any message to the Server, the Server responds with a list of IDs (each Client that connects gets a fresh ID).
What is actually happening:
The second Client that connects is able to see that there is a first Client that is already connected. But the first Client is not able to see that there is a second Client connected.
Thank you for your help.
The server loop
while(input.hasNextLine())
{
String result = "";
for(int i = 0; i < IDs.size(); i++)
{
result += (IDs.get(i) + " ");
}
output.println(result);
}
never calls input.nextLine(), which means that input.hasNextLine() is always true, so the server floods the socket with output until the buffer is full.
This can be seen by starting a client, killing the server, then keep pressing enter. The client keeps receiving data, even though the server is gone, until the buffer is emptied.
Add the following line inside the loop:
System.out.println(this.ID + ": " + input.nextLine());
This will make the server consume the line from the client, as was intended, and allow you to see / verify the data flowing.
I'm trying to connect all my clients to one server. I've done some research and found out that the easiest way to do it is create a new thread for every client that connects to the server. But I am already stuck on the part where a client disconnects and reconnect.
Client
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Test {
private static int port = 40021;
private static String ip = "localhost";
public static void main(String[] args) throws UnknownHostException,
IOException {
String command, temp;
Scanner scanner = new Scanner(System.in);
Socket s = new Socket(ip, port);
while (true) {
Scanner scanneri = new Scanner(s.getInputStream());
System.out.println("Enter any command");
command = scanner.nextLine();
PrintStream p = new PrintStream(s.getOutputStream());
p.println(command);
temp = scanneri.nextLine();
System.out.println(temp);
}
}
}
Server
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]) throws IOException {
String command, temp;
ServerSocket s1 = new ServerSocket(40021);
while (true) {
Socket ss = s1.accept();
Scanner sc = new Scanner(ss.getInputStream());
while (sc.hasNextLine()) {
command = sc.nextLine();
temp = command + " this is what you said.";
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
}
}
}
}
When I connect once it works correctly but as soon as I disconnect the client and try to reconnect (or connect a second client) it does not give an error or anything it just does not function. I am trying to keep it as basic as possible.
The output with one client:
When I try and connect a second client:
I hope someone could help me out. Thanks in advance.
Your server currently handles only 1 client at a time, use threads for each client, Modify your server code like this:-
public static void main(String[] args) throws IOException
{
ServerSocket s1 = new ServerSocket(40021);
while (true)
{
ss = s1.accept();
Thread t = new Thread()
{
public void run()
{
try
{
String command, temp;
Scanner sc = new Scanner(ss.getInputStream());
while (sc.hasNextLine())
{
command = sc.nextLine();
temp = command + " this is what you said.";
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
}
} catch (IOException e)
{
e.printStackTrace();
}
}
};
t.start();
}
}
I am making a java client/server socket program in netbeans that is supposed to accept a number and then return the square root/square the number.
It allows me to type in a number and then i get the following statement:
Exception found in Client: java.util.NoSuchElementException.
I am not sure why it is doing this, please help!
Here is my code for both classes:
Client:
package question1.clientserver;
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
try {
int number, temp;
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1", 1452);
Scanner sc1 = new Scanner(s.getInputStream());
System.out.println("Enter any number to be squared");
number = sc.nextInt();
PrintStream p = new PrintStream(s.getOutputStream());
p.println(number);
temp = sc1.nextInt();
System.out.println(temp);
} catch (Exception e) {
System.out.println("Exception found in Client: " + e);
}
}
}
and this is my server code
package question1.clientserver;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String[] args) {
while (true) {
System.out.println("Waiting for connection, please stand by...");
try {
int number, temp;
ServerSocket s1 = new ServerSocket(1452);
Socket ss = s1.accept();
System.out.println("Connection has been established");
Scanner sc = new Scanner(ss.getInputStream());
number = sc.nextInt();
temp = number * number;
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
} catch (Exception e) {
System.out.println("Exception in Server while creating connection" + e);
}
}
}
}
}
if you have any ideas or suggestions please let me know!
stacktrace
run: Enter any number to be squared
25 (which is what i type in for example)
Exception found in Client: java.util.NoSuchElementException
Build Successful (total time: 31 seconds)
I am trying to pass data from a String into a PrintWriter while simultaneously reading from a BufferedReader between two classes named Server.java and Client.java. My problem is that I am having trouble handling the exceptions that are being thrown from the block of code that reads data from the Scanner object (marked below).
Client.java
package root;
/**
* #author Noah Teshima
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private Socket clientSocket;
private BufferedReader bufferedReader;
private InputStreamReader inputStreamReader;
private PrintWriter printWriter;
private Scanner scanner;
public static void main(String[] args) {
new Client("localhost", 1025);
}
public Client(String hostName, int portNumber) {
try {
this.clientSocket = new Socket(hostName, portNumber);
this.bufferedReader = new BufferedReader(this.inputStreamReader = new InputStreamReader(this.clientSocket.getInputStream()));
this.printWriter = new PrintWriter(clientSocket.getOutputStream());
String msg = "",
msg2 = "";
this.printWriter.println(this.getClass());
this.printWriter.flush();
System.out.println(this.getClass().getName() + " is connected to " + this.bufferedReader.readLine());
while(!(msg = this.scanner.nextLine()).equals("exit")) { //Source of problem
this.printWriter.println(this.getClass().getName() + ": " + msg);
this.printWriter.flush();
while((msg2 = this.bufferedReader.readLine()) != null) {
System.out.println(msg2);
}
}
this.clientSocket.close();
}catch(IOException exception) {
exception.printStackTrace();
}
}
}
Stack trace::
Exception in thread "main" java.lang.NullPointerException
at root.Client.<init>(Client.java:47)
at root.Client.main(Client.java:25)
The code used to read from the BufferedReader and write to a PrintWriter is the same for both classes, so I only posted Client.java. If anyone would like to see the other class file, I would be happy to do so.
Before you use
while(!(msg = this.scanner.nextLine()).equals("exit")) { //Source of problem
You should have initialized the scanner.
The scanner object is null when you used it, and hence the NullPointerException.
I do not see a scanner = new Scanner(...); anywhere within your code,
maybe you have forgetten about it?