Below is my code for a simple Concurrent Server. Whenever I run multiple clients, the server only prints out the input of the first client. I'm not sure what I've done wrong. Any help would be appreciated.
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8001);
while (true){
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket);
ConcurrentServer client = new ConcurrentServer(clientSocket);
client.start();
}
} catch (IOException i){}
}
public void run(){
try {
inputStream = new BufferedReader(new InputStreamReader(concurrentSocket.getInputStream()));
outputStream = new PrintWriter(new OutputStreamWriter(concurrentSocket.getOutputStream()));
String testString = inputStream.readLine();
System.out.println(testString);
} catch (IOException i){}
}
This code might help you to understand how to run multiple clients concurrently. :)
What this code does? TCP Client sends a string to the server and TCP server sends back the string in UPPERCASE format & the server can do this concurrently with multiple connections.
I have included 3 files for the server and one more for testing the server with multiple clients(ClientTest.java)
Main.java
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
new Server(3000).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;
public class Server {
private ServerSocket sSocket;
private boolean run;
private int port;
public Server(int port) throws IOException {
this.port = port;
this.sSocket = new ServerSocket(this.port);
}
public void start() {
this.run = true;
Logger.getLogger(getClass().getName()).info("Server is listening on port: " + port);
try {
while (run) {
Socket cs = sSocket.accept();
Logger.getLogger(getClass().getName())
.info("New Client Connected! " + cs.getPort());
new Thread(new Client(cs)).start(); // Put to a new thread.
}
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe(e.getMessage());
}
}
public void stop() {
this.run = false;
}
}
Client.java (Client Process on server)
import java.io.*;
import java.net.Socket;
import java.util.logging.Logger;
public class Client implements Runnable {
private Socket clientSocket;
private DataOutputStream out; // write for the client
private BufferedReader in; // read from the client
public Client(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
// Do client process
outToClient(inFromClient().toUpperCase());
closeConnection();
}
private String inFromClient() {
String messageFromClient = "";
/*
* Do not use try with resources because once -
* - it exits the block it will close your client socket too.
*/
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
messageFromClient = in.readLine();
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe("InFromClientErr - " + e.getMessage());
}
return messageFromClient.trim().equals("") ? "No Inputs given!" : messageFromClient;
}
private void outToClient(String message) {
try {
out = new DataOutputStream(clientSocket.getOutputStream());
out.writeBytes(message);
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe("OutToClientErr - " + e.getMessage());
}
}
private void closeConnection() {
try {
in.close();
out.close();
clientSocket.close();
} catch (NullPointerException | IOException e) {
Logger.getLogger(getClass().getName()).severe(e.getMessage());
}
}
}
ClientTest.java (For Testing clients)
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ClientTest {
public static void main(String[] args) {
Socket clientSocket;
try {
clientSocket = new Socket("localhost", 3000);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(new Scanner(System.in).nextLine() + '\n'); // Get user input and send.
System.out.println(inFromServer.readLine()); // Print the server response.
} catch (IOException e) {
e.printStackTrace();
}
}
}
The issue was instead with the client. Not the server. The socket was declared outside of the for loop, and therefore only one connection was being created. Like so below:
public static void main(String[] args) {
try {
socket = new Socket("127.0.0.1", 8001);
for (int i = 0; i < 5; i++){
System.out.println("Starting client: " + i);
ConcurrentClient concurrentClient = new ConcurrentClient(socket, i);
concurrentClient.run();
}
} catch (IOException io) {
}
}
The Socket should be declared inside the for loop like so:
public static void main(String[] args) {
try {
for (int i = 0; i < 5; i++){
socket = new Socket("127.0.0.1", 8001);
System.out.println("Starting client: " + i);
ConcurrentClient concurrentClient = new ConcurrentClient(socket, i);
concurrentClient.run();
}
} catch (IOException io) {
}
}
I really don't know why you need so complex structure of input and output streams. It is better to use Scanner that will wait for the new input.
Also you can use PrintWriter to output the results of your conversation.
Here is server that accepts multiple clients:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ConcurrentServer extends Thread {
private Socket concurrentSocket;
public ConcurrentServer(Socket clientSocket) {
this.concurrentSocket = clientSocket;
}
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8001);
while (true){
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket);
ConcurrentServer client = new ConcurrentServer(clientSocket);
client.start();
}
} catch (IOException i){}
}
public void run(){
try {
InputStream inputStream = concurrentSocket.getInputStream();
Scanner scanner = new Scanner(inputStream);
OutputStream outputStream = concurrentSocket.getOutputStream();
PrintWriter pw = new PrintWriter(outputStream);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
pw.println("message: " + line);
pw.flush();
}
} catch (IOException i){}
}
}
Related
What I'm trying to do is make receiver class in the server which receives the sent messages from the client and make a sender class in the client. I'm trying to make the receiver in the server first 'cause I'll probably figure out how to do that in the client side after learning it. But doing this gives me java.net.BindException: Address already in use: JVM_Bind. I think it's because I have another Server server = new Server(); in the receiver. How do I solve this?
Server.java
package MultithreadingServerClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
ServerSocket serverSocket = new ServerSocket(3000);
Socket socket = serverSocket.accept();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
public Server() throws IOException {
}
public static void main(String[] args) {
Thread serverSender = new Thread(new ServerSender());
Thread serverReceiver = new Thread(new ServerReceiver());
serverSender.start();
serverReceiver.start();
}
}
// Sender class
class ServerSender implements Runnable {
#Override
public void run() {
try {
Server serve = new Server();
Scanner scanner = new Scanner(System.in);
String msg = "";
while (!msg.equalsIgnoreCase("exit")) {
System.out.print("Server: ");
msg = scanner.nextLine();
serve.printWriter.println(msg);
}
} catch (IOException e) {
System.err.println("Sender Error " + e);
}
}
}
class ServerReceiver implements Runnable {
#Override
public void run() {
try {
Server server = new Server();
System.out.println(server.bufferedReader.readLine());
} catch (IOException e) {
System.err.println("Receiver Error " + e);
}
}
}
Client.java
package MultithreadingServerClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
Socket socket = new Socket("localhost", 3000);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
public Client() throws IOException {
}
// Receive messages
public static void main(String[] args) {
try {
Client client = new Client();
while (true) {
System.out.println("Server: " + client.bufferedReader.readLine());
}
} catch (IOException e) {
System.out.println("Server Closed!");
}
}
}
class ClientSender implements Runnable {
#Override
public void run() {
try {
Client client = new Client();
client.printWriter.println("Test message: send to Server");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Don't create multiple instances of Server, you may create the instance in main then just pass the bufferedReader to the receiver class, and the printWriter to the sender class.
Sender class :
class ServerSender implements Runnable {
private PrintWriter writer;
public ServerSender(PrintWriter printWriter){
writer = printWriter;
}
#Override
public void run() {
try {
Scanner scanner = new Scanner(System.in);
String msg = "";
while (!msg.equalsIgnoreCase("exit")) {
System.out.print("Server: ");
msg = scanner.nextLine();
writer.println(msg);
}
} catch (IOException e) {
System.err.println("Sender Error " + e);
}
}
}
Receiver class :
class ServerReceiver implements Runnable {
private BufferedReader reader;
public ServerReceiver(BufferedReader bufferedReader){
reader = bufferedReader;
}
#Override
public void run() {
try {
System.out.println(reader.readLine());
} catch (IOException e) {
System.err.println("Receiver Error " + e);
}
}
}
Method main in Server :
public static void main(String[] args) {
Server serve = new Server();
Thread serverSender = new Thread(new ServerSender(serve.printWriter));
Thread serverReceiver = new Thread(new ServerReceiver(serve.bufferedReader));
serverSender.start();
serverReceiver.start();
}
You have two threads starting a new instance of the connection at the same port (3000). I assume that you are trying to have one thread receive a message from a server and another one for sending a message to client. I don't think you need to have a design like this. This can be done in a single threaded environment. There is no need for client (sender & receiver) and server (sender & receiver).
ServerSocket.accept(); method will listen to all the message incoming to the specified port number.
In order for the server to send reply to the client . You can use
DataOutputStream.writeUTF() & DataOutputStream.flush() method.
The same goes for client side. Have a look at the program below.
class Server {
public static void main(String args[]) throws IOException {
try (ServerSocket serverSocket = new ServerSocket(3333); // open connection at port 3333
Socket socket = serverSocket.accept();
DataInputStream inputStream = new DataInputStream(socket.getInputStream());) {
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String messageFromClient = "", messageToBeClient = "";
while (!messageFromClient.equals("exit")) {
messageFromClient = inputStream.readUTF();
System.out.println("Message From Client : " + messageFromClient);
messageToBeClient = reader.readLine();
outStream.writeUTF(messageToBeClient);
outStream.flush();
}
}
}
}
class Client {
public static void main(String args[]) throws Exception {
try (Socket socket = new Socket("localhost", 3333); // establish connection to the open socket at port 3333
DataInputStream inputStream = new DataInputStream(socket.getInputStream());) {
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String messageFromServer = "", messageToServer = "";
while (!messageToServer.equals("exit")) {
messageToServer = reader.readLine();
outStream.writeUTF(messageToServer);
outStream.flush();
messageFromServer = inputStream.readUTF();
System.out.println("Message From Server : " + messageFromServer);
}
}
}
}
does anyone know whats wrong with my code?
When I write something with client1 i just see it on the server and on the client1 but not on client2.
run() in Client.java:
public void run() {
Scanner input = new Scanner(System.in);
try {
Socket client = new Socket(host, port);
System.out.println("client started");
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
InputStream in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String i = input.nextLine();
writer.write(clientname + ": " + i + newline);
writer.flush();
String s = null;
while((s = reader.readLine()) != null) {
System.out.println(s);
}
writer.close();
reader.close();
client.close();
}
If you need the Server code or anything else just ask.
Thanks in advance!!
Additionally the Server:
public class Server {
public static void main(String[] args) {
int port = 40480;
int max = 10;
ExecutorService executor = Executors.newFixedThreadPool(max);
try {
ServerSocket server = new ServerSocket(port);
System.out.print("server started" + "\n");
while(true) {
try {
Socket client = server.accept();
executor.execute(new Handler(client));
}
catch (IOException e) {
e.printStackTrace();
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
And the Handler:
public class Handler implements Runnable{
private Socket client;
public Handler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
InputStream in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String s = null;
while((s = reader.readLine()) != null) {
writer.write(s + "\n");
writer.flush();
System.out.println(s);
}
writer.close();
reader.close();
client.close();
}
catch(Exception e) {
}
}
}
This is an example - it is not complete but should give you an idea how you could multicast output to a number of listening clients. There are better ways to do this, but I wrote it similar to how you appeared to be doing the sockets. It also lacks error checking in many places and I have left that as an exercise for the reader. This code was also written so that it can be used on Java 1.6 or higher.
The code uses a list of connected Clients maintained in the Server object. When input is received from one client, the output is multicast to each client in the Client list. Writing is done via a write method in the Client class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MulticastEchoServer {
List<Client> clientList = new LinkedList<Client>();
ExecutorService executor;
int port = 40480;
int max = 10;
public MulticastEchoServer() {
this.executor = Executors.newFixedThreadPool(max);
}
public void writeToAllClients(String string) throws IOException {
// Multiple threads access this so it must be in synchronized block
synchronized (this.clientList) {
Iterator<Client> iter = this.clientList.iterator();
while (iter.hasNext())
iter.next().write(string);
}
}
public void addClient(Client client) {
// Multiple threads access this so it must be in synchronized block
synchronized (this.clientList) {
clientList.add(client);
}
}
public void removeClient(Client client) {
// Multiple threads access this so it must be in synchronized block
synchronized (this.clientList) {
clientList.remove(client);
}
}
public void listen() {
try {
ServerSocket server = new ServerSocket(port);
System.out.println("server started and listening for connections");
while (true) {
try {
Socket socket = server.accept();
System.out.print("connection accepted" + "\n");
Client newClient = new Client(this, socket);
this.addClient(newClient);
this.executor.execute(newClient);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new MulticastEchoServer().listen();
}
private class Client implements Runnable {
Socket socket;
PrintWriter writer;
BufferedReader reader;
MulticastEchoServer server;
public Client(MulticastEchoServer server, Socket socket) throws IOException {
this.server = server;
this.socket = socket;
this.writer = new PrintWriter(this.socket.getOutputStream());
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
synchronized public void write(String string) throws IOException {
writer.write(string);
writer.flush();
}
public void close() {
this.writer.close();
try {
this.reader.close();
} catch (IOException e) {
}
try {
this.socket.close();
} catch (IOException e) {
}
}
#Override
public void run() {
System.out.println("Client Waiting");
String inString = null;
try {
while ((inString = this.reader.readLine()) != null) {
this.server.writeToAllClients(inString + "\n");
System.out.println(inString);
}
} catch (IOException e1) {
}
server.removeClient(this);
this.close();
System.out.println("Client Closed");
}
}
}
In your handler:
while((s = reader.readLine()) != null) {
writer.write(s + "\n");
writer.flush();
System.out.println(s);
}
You are only writing the string back to the sender, not to all connected sockets
I've spent lot of time to find out where is the problem but with no success. Server is launching correctly, but when I launch Client I get "Unexpected Error" exception. I've changed ports too with no effects. What should I do to make this working?
/* Server.java */
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 Server
{
private static final int PORT = 50000;
static boolean flaga = true;
private static ServerSocket serverSocket;
private static Socket clientSocket;
public static void main(String[] args) throws IOException
{
serverSocket = null;
try
{
serverSocket = new ServerSocket(PORT);
}
catch(IOException e)
{
System.err.println("Could not listen on port: "+PORT);
System.exit(1);
}
System.out.print("Wating for connection...");
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
while(flaga)
{
System.out.print(".");
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
//
}
System.out.println("\nClient connected on port "+PORT);
}
});
t.start();
clientSocket = null;
try
{
clientSocket = serverSocket.accept();
flaga = false;
}
catch(IOException e)
{
System.err.println("Accept failed.");
t.interrupt();
System.exit(1);
}
final PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
final BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
t = new Thread(new Runnable()
{
public void run()
{
try
{
Thread.sleep(5000);
while(true)
{
out.println("Ping");
System.out.println(System.currentTimeMillis()+" Ping sent");
String input = in.readLine();
if(input.equals("Pong"))
{
System.out.println(System.currentTimeMillis()+" Pong received");
}
else
{
System.out.println(System.currentTimeMillis()+" Wrong answer");
out.close();
in.close();
clientSocket.close();
serverSocket.close();
break;
}
Thread.sleep(5000);
}
}
catch(Exception e)
{
System.err.println(System.currentTimeMillis()+" Unexpected Error");
}
}
});
t.start();
}
}
and the Client class
/* Client.java */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client
{
private static final int PORT = 50000;
private static final String HOST = "localhost";
public static void main(String[] args) throws IOException
{
Socket socket = null;
try
{
socket = new Socket(HOST, PORT);
}
catch(Exception e)
{
System.err.println("Could not connect to "+HOST+":"+PORT);
System.exit(1);
}
final PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Thread t = new Thread(new Runnable()
{
public void run()
{
long start = System.currentTimeMillis();
while (true)
{
try
{
String input = in.readLine();
if (input != null)
{
System.out.println(System.currentTimeMillis() + " Server: " + input);
}
if (input.equals("Ping"))
{
if(System.currentTimeMillis()-start>30000)
{
out.println("Pon g");
System.out.println(System.currentTimeMillis() + " Client: Pon g");
break;
}
out.println("Pong");
System.out.println(System.currentTimeMillis() + " Client: Pong");
}
}
catch (IOException ioe)
{
//
}
}
}
});
t.start();
out.close();
in.close();
socket.close();
}
}
Here is the output on running
Wating for connection............
Client connected on port 50000
1368986914928 Ping sent
java.lang.NullPointerException
at Server$2.run(Server.java:84)
at java.lang.Thread.run(Thread.java:722)
You're making a big mistake with those catch blocks that are empty or print out your useless message.
You'll get more information if you print or log the stack trace. It's simply a must.
You need some intro instruction - have a look at this and see how it's different from yours.
http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html
It shows your out object is null. Instead of input.equals("Pong") use input != null && input.equals("Pong") in line 84 of Server.java. I guess you would have received Pong received but in later stages when you are listening to nothing you could have got this NPE.
I've been trying this for a while, and I want multiple clients to recieve multiple inputs simultaneously. There is one problem, I want the server to print "Hi" to all clients if one client says 'print2all Hi'.
I know how to process it to print it, just to print to ALL clients is the problem.
Here's what I have so far.
Server
try{
try{
server = new ServerSocket(25565);
} catch (Exception e){
e.printStackTrace();
}
while (isListening){
new SocketThread(server.accept()).start();
}
server.close();
} catch (Exception e){
e.printStackTrace();
}
SocketThread
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine, outputLine;
Processor kkp = new Processor();
out.println("Hi!");
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.Proccess(inputLine,this.socket);
out.println(outputLine);
}
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
Client
Processor p = new Processor();
socket = new Socket("localhost",25565);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
out.println("print2all Hi")
socket.close();
First you need to keep track of all connected clients:
final List<SocketThread> clients = new ArrayList<>();
while (isListening){
SocketThread client = new SocketThread(server.accept()).start();
clients.add(client);
}
Having such list if one client receives "print2all Hi" it simply iterates over all clients and sends message to each of them. To do this you'll most likely have to expose some method on SocketThread that will access client socket. This means you'll have to change out variable to field.
Alternative approach is to keep a list of client sockets. But this breaks encapsulation badly. Also you might run into nasty IO/thread-safety issues if sockets are exposed directly. Better hide them behind some API (like SocketThread method) and do the synchronization properly inside.
A full implementation of what you are looking.
Server
package tcpserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TCPServer {
private int serverPort = 25565;
private ServerSocket serverSocket;
private List<ConnectionService> connections = new ArrayList<ConnectionService>();
public TCPServer() {
try {
serverSocket = new ServerSocket(serverPort);
System.out.println("Waiting...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Connected: " + socket);
ConnectionService service = new ConnectionService(socket);
service.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new TCPServer();
}
class ConnectionService extends Thread {
private Socket socket;
private BufferedReader inputReader;
private PrintWriter outputWriter;
//private String username;
public ConnectionService(Socket socket) {
this.socket = socket;
try {
inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outputWriter = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
#Override
public void run() {
while (true) {
try {
String receivedMessage = inputReader.readLine();
System.out.println(receivedMessage);
StringTokenizer stoken = new StringTokenizer(receivedMessage);
String fargument = stoken.nextToken();
if (fargument.equals("print2all")) {
this.sendToAnyone(stoken.nextToken());
}
} catch (IOException ex) {
Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (NullPointerException e) {
System.out.println(e.getMessage());
} finally {
outputWriter.close();
}
}
}
protected void sendMessage(String message) {
outputWriter.println(message);
}
private void sendToAnyone(String message) {
for (ConnectionService connection : connections) {
connection.sendMessage(message);
}
}
}
}
Client
package tcpclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class tcpClient extends javax.swing.JFrame {
private Socket socket;
private BufferedReader inputReader;
private PrintWriter outputWriter;
public tcpClient() {
connectToServer();
}
private void connectToServer() {
try {
socket = new Socket(InetAddress.getByName("localhost"), 25565);
inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outputWriter = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
new Thread() {
#Override
public void run() {
receiveData();
}
}.start();
}
private void receiveData() {
try {
while (true) {
System.out.println(inputReader.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendData(String messageToSend) {
outputWriter.println(messageToSend);
}
public void closeSocket() {
if (socket != null) {
try {
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
tcpClient client = new tcpClient();
client.sendData("print2all Hi");
client.closeSocket();
}
});
}
}
I've just started with this section of the tutorial. I only have a basic understanding of what ports are, etc.
I tried to run this code:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
"Don't know about host: taranis.
Java Result: 1"
Is the error catch I get. From my limited understanding; is the echo-server something which exists on my machine? If that's the case, what do I need to do to get this running? Or am I way off?
Also why have they chosen "taranis" as a parameter?
Ive also replaced "taranis" with "localhost" to see what happened.
It ended up catching an IOException this time.
EDIT: So I've found that the echo server is disabled by default in win7 and have activated it. However I cant even connect to it on telnet. I think I may just be in over my head. I've also tried the sockets you have recommended with no success.
From the same tutorial:
... The Socket constructor used here requires the name of the machine and the port number to which you want to connect. The example program uses the host name taranis. This is the name of a hypothetical machine on our local network. When you type in and run this program on your machine, change the host name to the name of a machine on your network. Make sure that the name you use is the fully qualified IP name of the machine to which you want to connect. The second argument is the port number. Port number 7 is the port on which the Echo server listens.`
In any case, you will probably want to change taranis to "localhost" and make sure an echo service is running on your machine. If it's not, you could use something like the following code to simulate an echo server.
import java.net.Socket;
import java.util.Formatter;
import java.util.Scanner;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class EchoServer {
public static void main(String[] args) {
try {
new EchoServer(INSERTPORT).execute();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private ServerSocket serverSocket;
private int port;
private ArrayList<Client> clientList;
private ExecutorService clientRunner;
public EchoServer(int port) throws IOException {
this.port = port;
serverSocket = new ServerSocket(port);
clientRunner = Executors.newCachedThreadPool();
clientList = new ArrayList<>();
}
public void sendMessageToAll(String message) {
for (Client c : clientList) {
c.displayMessage(message);
}
}
public void execute() throws IOException {
while (true) {
clientList.add(new Client(serverSocket.accept(), this));
clientRunner.execute(clientList.get(clientList.size()-1));
}
}
private class Client implements Runnable {
private Socket clientSocket;
private Scanner input;
private Formatter output;
public Client(Socket s) throws IOException {
clientSocket = s;
input = new Scanner(clientSocket.getInputStream());
output = new Formatter(clientSocket.getOutputStream());
}
public void displayMessage(String s) {
output.format(s + "\n");
output.flush();
}
#Override
public void run() {
while(clientSocket.isConnected()) {
if(input.hasNextLine()) {
sendMessageToAll(input.nextLine());
}
}
}
}
}
Edit: Just for completeness, as you mentioned some problems running the code, you run the server (this code) and leave it running in the background, then run the client (the code you posted). I tested it, works fine.
Try this,
Use the loopback address of 127.0.0.1 instead of taranis.
Use port higher than 1024, something like 4444, 8333 etc....
I am also adding my code that i used to learn Client Server Commnu
Client Side Code:
public class ClientWala {
public static void main(String[] args) throws Exception{
Boolean b = true;
Socket s = new Socket("127.0.0.1", 4444);
System.out.println("connected: "+s.isConnected());
OutputStream output = s.getOutputStream();
PrintWriter pw = new PrintWriter(output,true);
// to write data to server
while(b){
if (!b){
System.exit(0);
}
else {
pw.write(new Scanner(System.in).nextLine());
}
}
// to read data from server
InputStream input = s.getInputStream();
InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);
String data = null;
while ((data = br.readLine())!=null){
// Print it using sysout, or do whatever you want with the incoming data from server
}
}
}
Server Side Code:
public class ServerTest {
ServerSocket s;
public void go() {
try {
s = new ServerSocket(44457);
while (true) {
Socket incoming = s.accept();
Thread t = new Thread(new MyCon(incoming));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
class MyCon implements Runnable {
Socket incoming;
public MyCon(Socket incoming) {
this.incoming = incoming;
}
#Override
public void run() {
try {
PrintWriter pw = new PrintWriter(incoming.getOutputStream(),
true);
InputStreamReader isr = new InputStreamReader(
incoming.getInputStream());
BufferedReader br = new BufferedReader(isr);
String inp = null;
boolean isDone = true;
System.out.println("TYPE : BYE");
System.out.println();
while (isDone && ((inp = br.readLine()) != null)) {
System.out.println(inp);
if (inp.trim().equals("BYE")) {
System.out
.println("THANKS FOR CONNECTING...Bye for now");
isDone = false;
s.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
try {
s.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ServerTest().go();
}
}