I am trying to implement Client to Client which passes through the server. Client1 sends a line to the server and server forwards it to all the other clients.
Can you point out my mistake. Nothing is printed on the other clients.
Server Code:
public class Server {
int port;
ServerSocket server=null;
Socket socket=null;
ExecutorService exec = null;
ArrayList clients = new ArrayList();
DataOutputStream dos=null;
public static void main(String[] args) throws IOException {
Server serverobj=new Server(2000);
serverobj.startServer();
}
Server(int port){
this.port=port;
exec = Executors.newFixedThreadPool(3);
}
public void startServer() throws IOException {
server=new ServerSocket(2000);
System.out.println("Server running");
while(true){
socket=server.accept();
dos = new DataOutputStream(socket.getOutputStream());
clients.add(dos);
ServerThread runnable= new ServerThread(socket,new ArrayList<>(clients),this);
exec.execute(runnable);
}
}
private static class ServerThread implements Runnable {
Server server=null;
Socket socket=null;
BufferedReader brin;
Iterator it=null;
Scanner sc=new Scanner(System.in);
String str;
ServerThread(Socket socket, ArrayList clients ,Server server ) throws IOException {
this.socket=socket;
this.server=server;
System.out.println("Connection successful with "+socket);
brin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
it = clients.iterator();
}
#Override
public void run() {
try{
while ((str = brin.readLine()) != null) {
while (it.hasNext()) {
try{
DataOutputStream dost=(DataOutputStream) it.next();
dost.writeChars(str);
dost.flush();
}
catch(IOException ex){
System.out.println("Error 1 "+ex);
}
}
}
brin.close();
socket.close();
}
catch(IOException ex){
System.out.println("Error 2 "+ex);
}
}
}
}
Client 1 code:
public class Client1 {
public static void main(String args[]) throws IOException{
String str;
Socket socket=new Socket("127.0.0.1",2000);
PrintStream prout=new PrintStream(socket.getOutputStream());
BufferedReader bread=new BufferedReader(new InputStreamReader(System.in));
BufferedReader dis=new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
System.out.println("Send to others:");
str=bread.readLine();
prout.println(str);
}
}
}
Other Clients:
public class Client2 {
public static void main(String args[]) throws IOException{
String str;
Socket socket=new Socket("127.0.0.1",2000);
BufferedReader dis=new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
str=dis.readLine();
System.out.print("Message: "+str+"\n");
}
}
}
Please help.. I have been at it for 2 days...
Related
i have an ISO8583 message to send between a client and a server (through sockets). What i did is declare socket and serverSockets classes, start server and accept connections, then create channel both on server and client to apply receive and send methods.
What i got is i cannot print the iso8583 message i send. here is the complete code :
The server's side code :
public class SocketServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port) throws IOException, ISOException {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
ISOChannel channel = new ASCIIChannel (
"localhost", 5000, new ISO87APackager() );
channel.connect();
ISOMsg r = channel.receive ();
System.out.println("isoMsg result "+r.getMTI());
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String data = in.readLine();
System.out.println("Inside Server Socket: " + data);
out.println("Data from server: " + data);
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
public static void main(String[] args) throws IOException, ISOException {
SocketServer server = new SocketServer();
server.start(5000);
System.out.println("Server start...");
}
}
and the client's code :
public class Client
{
public Client(String address, int port) throws ISOException
{
// establish a connection
try
{
Socket socket = new Socket(address, port);
System.out.println("Connected");
ISOChannel channel = new ASCIIChannel (
"localhost", 5000, new ISO87APackager() );
channel.connect();
ISOMsg r=new ISOMsg();
r.setMTI("0200");
channel.send(r);
InputStream in2= socket.getInputStream();
OutputStream out2=socket.getOutputStream();
String line = "";
try
{
in2.close();
out2.close();
socket.close();
}
catch(IOException i)
{
i.printStackTrace();
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String args[]) throws ISOException
{
Client client = new Client("localhost", 5000);
}
}
This is code provided to me for a class. I am trying trying to fix a connection problem between the client and server. Even when both are started they do not connect.
This is for a Java based game of Battleship that will allow two users on separate devices to play one another. I'm not sure why the two do not connect and even the debugger has not been much help in directing me to the problem.
public class GameClient
{
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void openConnection(String ip, int port)
{
try
{
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
catch (Exception e)
{
System.out.println("Error opening client socket");
}
}
public String sendMessage(String msg)
{
String resp = "";
try
{
out.println(msg);
resp = in.readLine();
}
catch (Exception e)
{
System.out.println("Error sending message from Client");
}
return resp;
}
public void stop()
{
try
{
in.close();
out.close();
clientSocket.close();
}
catch (Exception e)
{
System.out.println("Error stopping client");
}
}
public static void main(String[] args)
{
GameClient client = new GameClient();
client.openConnection("10.7.232.200", 3333);
String response = client.sendMessage("1,2");
System.out.println(response);
client.stop();
}
}
public class GameServer
{
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port)
{
try
{
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String move = in.readLine();
System.out.println(move);
out.println("6,1");
}
catch (Exception e)
{
System.out.println("Socket opening error");
}
}
public void stop()
{
try
{
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
catch (Exception e)
{
System.out.println("Error closing sockets");
}
}
public static void main(String [] args)
{
GameServer server = new GameServer();
server.start(3333);
server.stop();
}
}
public class PlayBattleship
{
public static void main(String[] args)
{
GameClient client = new GameClient();
client.openConnection("10.7.232.200", 3333);
//System.out.println(response);
BattleshipGame game = new BattleshipGame();
while (!game.checkEndgame())
{
game.getGuess(client);
}
client.stop();
}
}
The client and server should connect and stay connected till the game has reached completion
EDIT: I have thoroughly read the API documentation but still cannot understand the problem.
The Server in your code isn't waiting for the incoming requests, it only serves a single incoming request and then kills itself due to the nature of the main method which starts it.
You need to have the server wait for the requests and do not die. Check the code snippet below to understand the logic.
Plus, always try to throw the exceptions if you can't do anything meaningful with it within the method it is caught in. In your code the main method of the server will anyway execute even if there is an exception caught in the start method
public class GameServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public ServerSocket start(int port) throws IOException {
serverSocket = new ServerSocket(port);
return serverSocket;
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
// This method accepts and serves the incoming requests
public void acceptConnection(ServerSocket serverSocket) throws IOException {
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String move = in.readLine();
System.out.println(move);
out.println("6,1");
}
public static void main(String[] args) throws IOException {
GameServer server = new GameServer();
ServerSocket serverSocket = server.start(3333);
System.out.println("Server Started");
// The effective change you need to make
// Loop through the incoming requests
while(true) {
server.acceptConnection(serverSocket);
}
}
}
public class GameClient {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void openConnection(String ip, int port) throws IOException {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public String sendMessage(String msg) throws IOException {
String resp = "";
out.println(msg);
resp = in.readLine();
return resp;
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
}
public static void main(String[] args) throws IOException {
GameClient client = new GameClient();
client.openConnection("10.7.232.200", 3333);
String response = client.sendMessage("1,2");
System.out.println(response);
client.stop();
}
}
I have written a simple multithreaded Server on which the two Clients can send Messages to the Server an the Server a Message to all the Clients at once. But I can't get it to work as intended.
I already tried it by putting a List of all PrintWriters in the Server class and then print the Message through each PrintWriter but this didn't work either.
public class Client
{
private static final String IP = "10.59.0.188";
private Socket clientSocket;
private PrintWriter toServer;
private BufferedReader fromServer;
private BufferedReader input;
private String serverMessage;
private String clientMessage;
private String name;
public static void main(String[] args) {
try {
new Client();
} catch (Exception e) {
System.err.println(e);
}
}
public Client() throws IOException {
input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Name: ");
name = input.readLine();
openConnection();
toServer.println(name);
while (true) {
clientMessage = input.readLine();
toServer.println(clientMessage);
}
//closeConnection();
}
private void openConnection() throws IOException{
clientSocket = new Socket(IP, 6666);
toServer = new PrintWriter(clientSocket.getOutputStream(), true);
fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
}
public class Server {
private ServerSocket serverSocket;
private BufferedReader input;
private Vector<ClientProcess> processList;
private int clientCount = 0;
private String serverMessage;
public static void main(String[] args) {
try {
new Server();
} catch (Exception e) {
System.err.println(e);
}
}
public Server() throws IOException {
startServer();
while (clientCount < 2) {
waitForNewClient();
}
for (ClientProcess clientProcess : processList) {
clientProcess.start();
System.out.println("Clientprocess started");
}
}
private void startServer() throws IOException {
processList = new Vector<>();
input = new BufferedReader(new InputStreamReader(System.in));
serverSocket = new ServerSocket(6666);
System.out.println("Server online");
}
private void waitForNewClient() throws IOException {
System.out.println("Waitin' for new Client...");
Socket clientSocket = serverSocket.accept();
ClientProcess clientProcess = new ClientProcess(clientSocket);
processList.add(clientProcess);
clientCount++;
}
}
public class ClientProcess extends Thread {
private Socket clientSocket;
private PrintWriter toClient;
private BufferedReader fromClient;
private String clientMessage;
private String serverMessage;
private String name;
private BufferedReader input;
public ClientProcess(Socket clientSocket) {
this.clientSocket = clientSocket;
input = new BufferedReader(new InputStreamReader(System.in));
}
#Override
public void run() {
try {
openClientConnection();
name = fromClient.readLine();
do {
clientMessage = fromClient.readLine();
System.out.println(name + ": " + clientMessage);
} while (true);
//closeClientConnection();
} catch (IOException e) {
System.err.println(e);
}
}
private void openClientConnection() throws IOException {
toClient = new PrintWriter(clientSocket.getOutputStream());
fromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
serverMessage = "ServerMessageTest00";
toClient.println(serverMessage);
System.out.println("Client Connection Online");
}
}
In the ClientProcess you create a new PrintWriter.
From the javadoc:
Creates a new PrintWriter, without automatic line flushing, from anexisting OutputStream.
This means your toClient.println(...); is wrote to the server's output buffer but will not be send to the client because you miss the toClient.flush().
I made a simple chat program where sending data from MyClient to MyServer is working, but when sending data from MyServer to MyClient is not working. So where I'm making mistake?
This is MyServer program:
import java.io.*;
import java.net.*;
public class MyServer{
ServerSocket ss;
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyServer(){
try{
System.out.println("Server START......");
ss=new ServerSocket(9000);
s=ss.accept();
System.out.println("Client Connected.....");
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
chat();
}
catch(Exception e){
System.out.println(e);}
}
public void chat()throws IOException{
String str=" ";
do{
str=din.readUTF();
System.out.println("Client Message: "+str);
dout.writeUTF("I have recieved ur message:"+str);
dout.flush();
}while(!str.equals("stop"));
}
public static void main(String arg[]){
new MyServer();}
}
This is MyClient program:
import java.io.*;
import java.net.*;
public class MyClient{
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyClient(){
try{
s=new Socket("localhost",9000);
System.out.println(s);
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
chat();
}catch(Exception e){
System.out.println(e);}
}
public void chat()throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1;
do{
s1=br.readLine();
dout.writeUTF(s1);
dout.flush();
System.out.println("Server Message: "+din.readUTF());
}while(!s1.equals("stop"));
}
public static void main(String arg[]){
new MyClient();}
}
Actually you already do send an information from the server to the client with "I have received your message..."...
Anyway. If you want to send messages from the server to the client like a chat program your code should looks like this:
The Server part:
public class Server {
ServerSocket ss;
Socket s;
DataInputStream din;
DataOutputStream dout;
public Server() {
try {
System.out.println("Server START......");
ss = new ServerSocket(9000);
s = ss.accept();
System.out.println("Client Connected.....");
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
chat();
} catch (Exception e) {
System.out.println(e);
}
}
public void chat() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s1;
do {
System.out.println("Client Message: " + din.readUTF());
s1=br.readLine();
dout.writeUTF(s1);
dout.flush();
} while (!s1.equals("stop"));
}
public static void main(String arg[]) {
new Server();
}
}
And for the client:
public class Client {
Socket s;
DataInputStream din;
DataOutputStream dout;
public Client() {
try {
s = new Socket("localhost", 9000);
System.out.println(s);
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
chat();
} catch (Exception e) {
System.out.println(e);
}
}
public void chat() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s1;
do {
s1 = br.readLine();
dout.writeUTF(s1);
dout.flush();
System.out.println("Server Message: " + din.readUTF());
} while (!s1.equals("stop"));
}
public static void main(String arg[]) {
new Client();
}
}
I need to create a program where a peer needs to communicate with other peer. I have vaguely created a structure but it does not work. I know I am making a mistake but not able to figure out the problem. I create a server socket as a thread and create a client socket thread which will talk to the server socket thread. after I enter a port, the program does nothing...
server.java
------------
class server
{
public static void main(String argv[]) throws Exception
{
//server socket
ServerSocket server = new ServerSocket(1001);
Socket client;
while(true)
{
client = server.accept();
Thread t = new Thread(new acceptconnection(client));
t.start();
}
}
}
class acceptconnection implements Runnable
{
BufferedReader inFromClient,inn;
DataOutputStream ds;
Socket clientsocket;
acceptconnection (Socket socket) throws IOException
{
this.clientsocket = socket;
inn = new BufferedReader (new InputStreamReader(System.in));
inFromClient =new BufferedReader(new
InputStreamReader(clientsocket.getInputStream()));
ds = new DataOutputStream(clientsocket.getOutputStream());
}
#Override
public void run ()
{
try
{
String clientSentence, inp;
while(( clientSentence = inFromClient.readLine())!=null)
{
System.out.println("message from remote socket #" +
clientsocket.getRemoteSocketAddress()+ clientSentence);
inp=inn.readLine();
ds.writeBytes(inp + "\n");
ds.flush();
}
}
}
}
client.java
------------
class client
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
Socket clientSocket = null;
// ss = new ServerSocket(10002);
clientSocket = new Socket("localhost", 1001);
BufferedReader inFromUser = new BufferedReader( new
InputStreamReader(System.in));
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
System.out.println("Enter you name:");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + "\n" );
System.out.println("Enter the port u want:");
sentence = inFromUser.readLine();
int serverport = Integer.parseInt(sentence);
Thread t = new Thread(new acceptconnection1(serverport));
t.start();
String msg;
clientSocket.close();
}
}
class acceptconnection1 implements Runnable {
BufferedReader inserver, inn;
DataOutputStream ds;
Socket socket, peersocket;
int serverport ;
Socket clientSocket = null;
acceptconnection1 (int serverport) throws IOException{
this.serverport = serverport;}
public void run () {
ServerSocket ss;
String cs,a;
try {
ss = new ServerSocket(serverport);
while(true)
{
peersocket =ss.accept();
Thread t = new Thread(new abc(peersocket) );
t.start();
}}}
class abc implements Runnable {
BufferedReader inn,inp;
DataOutputStream ds;
Socket peersocket;
public abc(Socket peersocket) throws IOException{
this.peersocket = peersocket;
inn = new BufferedReader (new InputStreamReader(System.in));
inp =new BufferedReader(new InputStreamReader(peersocket.getInputStream()));
ds = new DataOutputStream(peersocket.getOutputStream());
}
#Override
public void run()
{
String clientSentence;
Socket client = new Socket();
try {
while(( clientSentence = inp.readLine())!=null)
{
ds.writeBytes("wake up!");
//System.out.println("message=" + clientSentence);
}