Socket Programming Implementation Using Threading in Java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
Here I can solve socket programming for chat application between multiple client and server where client can send multiple message to the server. But now I want to solve a new problem where conversion of any string from any client [each client can send at most 2 messages] into a FULL UPPERCASE string with the help of the server. The server will be able to serve at most 5 clients.
This is my client coe.....
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
System.out.println("Client started..");
Socket socket = new Socket("127.0.0.1", 22222);
System.out.println("Client Connected..");
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
while (true) {
Scanner sc = new Scanner(System.in);
String message = sc.nextLine();
if(message.equals("exit")){
break;
}
//sent to server...
oos.writeObject(message);
try {
//receive from server..
Object fromServer = ois.readObject();
System.out.println("From Server: " + (String) fromServer);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
socket.close();
}
}
This is my server code........
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(22222);
System.out.println("Server Started..");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected..");
// new Server Thread Start.....
new ServerThread(socket);
}
}
}
class ServerThread implements Runnable {
Socket clientSocket;
Thread t;
ServerThread(Socket clientSocket) {
this.clientSocket = clientSocket;
t = new Thread(this);
t.start();
}
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
while (true) {
//read from client...
Object cMsg = ois.readObject();
if (cMsg == null)
break;
System.out.println("From Client: " + (String) cMsg);
String serverMsg = (String) cMsg;
serverMsg = serverMsg.toUpperCase();
//send to client..
oos.writeObject(serverMsg);
}
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

// Sever side
package sockettreading;
import java.io.*;
import java.net.*;
/**
*
* #author Amanur Rahman
*/
public class SocketTreading {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5050);
System.out.println("Server is starting...");
int cn=1;
while (cn<=5) {
Socket s = ss.accept();
System.out.println("Client"+cn+" is connected \n" + s);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Assinging new thread for this client");
Thread t = new ClientHandler(s, dis, dos);
t.start();
cn++;
}
System.out.println("Client limit cross");
ss.close();
}
}
class ClientHandler extends Thread {
final Socket soc;
final DataInputStream input;
final DataOutputStream output;
int i = 1;
public ClientHandler(Socket s, DataInputStream dis,
DataOutputStream dos) {
this.soc = s;
this.input = dis;
this.output = dos;
}
#Override
public void run() {
String received;
String ends;
String toreturn;
while (i <= 2) {
try {
output.writeUTF("Please write your message : ");
String str = input.readUTF();
System.out.println("Client msg is: "+ str.toUpperCase());
output.writeUTF("Do you want to exit or continue ( if exit type \"ENDS\" ) ");
ends = input.readUTF();
if (ends.equals("ENDS")) {
System.out.println("Client" + this.soc + "send exit.");
this.soc.close();
System.out.println("Connection closed");
break;
}
} catch (IOException e) {
System.out.println(e);
}
System.out.println("" + i);
i++;
}
try {
this.input.close();
this.output.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
// client side
package sockettreading;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
/**
*
* #author Amanur Rahman
*/
public class ClientThreading {
public static void main(String[] args) throws IOException {
try(Socket s = new Socket("localhost", 5050);){
System.out.println("Connected");
Scanner scn = new Scanner(System.in);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
int i = 1;
while (i <= 2) {
System.out.println(dis.readUTF());
String num1 = scn.nextLine();
dos.writeUTF(num1);
System.out.println(dis.readUTF());
String num2 = scn.nextLine();
dos.writeUTF(num2);
System.out.println(dis.readUTF());
String ends = scn.nextLine();
dos.writeUTF(ends);
if (ends.equals("ENDS")) {
System.out.println("Closing the connection" + s);
s.close();
System.out.println("Connection closed");
break;
}
i++;
}
System.out.println(dis.readUTF());
s.close();
dos.close();
dis.close();
}
catch (IOException ex) {
if(ex.getMessage()!=null){
System.out.println("Already 5 clients are served so the server is closed: ");
}else{
System.out.println("Client 2 message already send. That's way the connection closed.");
}
}
}
}

Related

Java IOException Stream Closed in Server Client program

I am trying to make a Server Client program that allows sending multiple messages from server to client or vice versa without waiting for a response. The program works fine when the first client is connected and disconnected. But when I connect the client again, I get the error. Here is my server code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
class Q2Server implements Runnable{
private ServerSocket serverSocket;
private Socket socket;
private DataOutputStream out;
private BufferedReader in1;
private DataInputStream in2;
private Thread read, write;
private String clientMsg, serverMsg;
public Q2Server (int port) throws IOException{
serverSocket = new ServerSocket(port);
while(true) {
try {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
socket = serverSocket.accept();
System.out.println("Just connected to " + socket.getRemoteSocketAddress());
out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("Thanks for connecting to " + socket.getLocalSocketAddress());
clientMsg = "";
serverMsg = "";
read = new Thread(this);
write = new Thread(this);
read.start();
write.start();
read.join();
write.join();
} catch(IOException e) {
e.printStackTrace();
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
public void run () {
try {
if(Thread.currentThread() == write) {
while(true) {
try {
if(clientMsg.equals("close")) {
break;
} else {
in1 = new BufferedReader(new InputStreamReader(System.in));
out = new DataOutputStream(socket.getOutputStream());
serverMsg = in1.readLine();
out.writeUTF(serverMsg);
if(serverMsg.equals("close")) {
socket.close();
in1.close();
in2.close();
out.close();
System.out.println("Closing connection...");
break;
}
}
} catch (SocketException s) {
break;
}
}
} else {
while(true) {
try {
if(serverMsg.equals("close")) {
break;
}
in2 = new DataInputStream(socket.getInputStream());
clientMsg = in2.readUTF();
System.out.println("Client: " + clientMsg);
if(clientMsg.equals("close")) {
socket.close();
in1.close();
in2.close();
out.close();
System.out.println("Closing connection...");
break;
}
} catch(SocketException s) {
break;
}
}
}
} catch (IOException i) {
i.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Q2Server server = new Q2Server(8080);
}
}
Client code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.rmi.UnexpectedException;
import java.io.InputStreamReader;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.lang.Thread;
class Q2Client implements Runnable {
private Socket socket;
private Thread read, write;
private BufferedReader in1;
private DataInputStream in2;
private DataOutputStream out;
private String clientMsg, serverMsg;
public Q2Client(int port) {
try {
socket = new Socket("localHost",port);
System.out.println("Connected to port: " + port);
clientMsg = serverMsg = "";
read = new Thread(this);
write = new Thread(this);
in2 = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
System.out.println(in2.readUTF());
read.start();
write.start();
read.join();
write.join();
} catch(UnexpectedException u) {
u.printStackTrace();
} catch(IOException i) {
i.printStackTrace();
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
public void run() {
try {
if(Thread.currentThread() == write) {
while(true) {
try {
if(serverMsg.equals("close")) {
break;
}
in1 = new BufferedReader(new InputStreamReader(System.in));
out = new DataOutputStream(socket.getOutputStream());
clientMsg = in1.readLine();
out.writeUTF(clientMsg);
if(clientMsg.equals("close")) {
socket.close();
in1.close();
in2.close();
out.close();
System.out.println("Closing connection...");
break;
}
} catch (SocketException s) {
break;
}
}
} else {
while(true) {
try {
if(clientMsg.equals("close")) {
break;
}
in2 = new DataInputStream(socket.getInputStream());
serverMsg = in2.readUTF();
System.out.println("Server: " + serverMsg);
if(serverMsg.equals("close")) {
socket.close();
in1.close();
in2.close();
out.close();
System.out.println("Closing connection...");
break;
}
} catch (SocketException s) {
break;
}
}
}
} catch (IOException i) {
i.printStackTrace();
}
}
public static void main(String[] args) {
Q2Client client = new Q2Client(8080);
}
}
Here is the stacktrace of the exception:
java.io.IOException: Stream closed
at java.base/java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:176)
at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:342)
at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.base/java.io.InputStreamReader.read(InputStreamReader.java:185)
at java.base/java.io.BufferedReader.fill(BufferedReader.java:161)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:326)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:392)
at Q2Server.run(Q2Server.java:65)
at java.base/java.lang.Thread.run(Thread.java:835)
When either of the server or client sends "close" the connection closes. The client can connect again. But when I run the client code again, I get the exception. What is going wrong and how do I fix this?
You're getting an exception because you're trying to read from a BufferedReader which no longer exists, the in1 in particular. At the first run, all your streams and readers open as they should, but after getting the command close from the client, your server closes the in1. Then, when the client tries to reconnect, the program tries to assign the value of in1.readLine() to serverMsg which is a String, but since in1 is no more, the IOException occurs since the BufferedReader is closed and nothing can be read from it.
I suppose since you want to leave the server running while the client(s) can connect and disconnect at any given time, which totally makes sense, maybe you shouldn't close the BufferedReader which supplies keyboard commands to the server in your case. Closing it doesn't make sense to me, since you're not stopping the whole server when the client disconnects, you just close the connection, but the server still should be able to accept commands.
Hope this helps.

Java Concurrent Socket Programming

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){}
}
}

Multi Client chat Server Java

i am coding a multi client chat server.i have a server folder that contains Server.java and three client folders namely client1,client2,client3 containing java files resp.now when every client joins the server i try to send a text but the server does not picks the message.the problem is in the void run() try method. till the while(true) loop everything works.
Server code:
Chat.java
import java.net.*;
import java.io.*;
import java.util.*;
class Chat implements Runnable {
Socket skt = null;
DataInputStream dis = null;
DataOutputStream dos = null;
PrintWriter pw = null;
TreeMap<Socket, String> tm;
public Chat(Socket skt, TreeMap<Socket, String> tm) {
this.skt = skt;
this.tm = tm;
}
public void run() {
try {
dis = new DataInputStream(skt.getInputStream());
String msg = "";
while (true) {
msg = dis.readUTF();
Set s = tm.keySet();
Iterator itr = s.iterator();
while (itr.hasNext()) {
String k = (String) itr.next();
Socket v = (Socket) tm.get(k);
dos = new DataOutputStream(v.getOutputStream());
dos.writeUTF();
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
dis.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
Server.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.TreeMap;
class Server
{
public static void main(String dt[])
{
ServerSocket sskt=null;
Socket skt=null;
DataInputStream dis=null;
DataOutputStream dos=null;
TreeMap <String,Socket>tm=new TreeMap<String,Socket>();
try
{
sskt=new ServerSocket(1234);
System.out.println("Waiting for Clients");
while(true)
{
skt=sskt.accept();
dis=new DataInputStream(skt.getInputStream());
dos=new DataOutputStream(skt.getOutputStream());
String user=dis.readUTF();
String pass=dis.readUTF();
if(user.equals(pass))
{
dos.writeBoolean(true);
tm.put(user,skt);
Chat ch=new Chat(skt,tm);
Thread t=new Thread(ch);
t.start();
}
else
{
dos.writeBoolean(false);
}
} //end of while.
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
try
{
dos.close();
dis.close();
skt.close();
sskt.close();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
}
Client Code:
Send.java
import java.io.*;
import java.net.*;
class Send implements Runnable {
Socket skt = null;
public Send(Socket skt) {
this.skt = skt;
System.out.println(skt);
}
public void run() {
InputStreamReader isrout = null;
BufferedReader brout = null;
PrintWriter pw = null;
DataInputStream dis = null;
try {
// Thread.sleep(2000);
System.out.println("Send a text");
isrout = new InputStreamReader(System.in);
brout = new BufferedReader(isrout);
pw = new PrintWriter(skt.getOutputStream(), true);
do {
String msg = brout.readLine();
pw.println(msg);
} while (!msg.equals("bye"));
} catch (Exception e) {
System.out.println(e);
} finally {
try {
pw.close();
brout.close();
isrout.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
Client1.java
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
class Client1 {
public static void main(String dt[]) {
Socket skt = null;
InputStreamReader isr = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
skt = new Socket("127.0.0.1", 1234);
System.out.println("Connected to server");
System.out.println(skt);
isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
dos = new DataOutputStream(skt.getOutputStream());
dis = new DataInputStream(skt.getInputStream());
System.out.println("Enter a username");
String user = br.readLine();
dos.writeUTF(user);
System.out.println("Enter a password");
String pass = br.readLine();
dos.writeUTF(pass);
if (dis.readBoolean()) {
System.out.println("User Authenticated");
} else {
System.out.println("Incorrect username or password");
}
Send sn = new Send(skt);
Thread t = new Thread(sn);
t.start();
} catch (Exception e) {
System.out.println(e);
} finally {
try {
// skt.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
After writing any value using an outputstream you need to flush it to actually send it.
In the Chat and Server class where you use DataOutputStream, you need to call this after writing data.
dos.flush();
In the Client class after sending data through the PrintWriter you need to call this.
pw.flush();

Exampels on a Server-Client-Chat applikation on JAVA [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
I have been "googeling" around for a long time for examples over Server-client-chat application, but I can't really understand them. Many of them are using a class and creates the GUI from it, and I don't want to copy straight from it. Alot of examples doesn't either really explain how you send messages from a client to the server and then it sends the message out to all the other clients.
I am using NetBeans and I was wondering if there is some good tutourials or examples that can help me with this?
Here comes the multiThreading program :) the server has two classes, and client has one. Hope you Like it!
SERVER MAIN CLASS:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException {
int MAXCLIENTS = 20;
int port = 4444;
ServerSocket server = null;
Socket clientSocket = null;
// An array of clientsConnected instances
ClientThread[] clientsConnected = new ClientThread[MAXCLIENTS];
try {
server = new ServerSocket(port);
System.out.println("listening on port: " + port);
} catch (IOException e) {// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
clientSocket = server.accept();
} catch (IOException e) {
e.printStackTrace();
if (!server.isClosed()){server.close();}
if (!clientSocket.isClosed()){clientSocket.close();}
}
System.out.println("Client connected!");
for (int c = 0; c < clientsConnected.length; c++){
if (clientsConnected[c] == null){
// if it is empty ( null) then start a new Thread, and pass the socket and the object of itself as parameter
(clientsConnected[c] = new ClientThread(clientSocket, clientsConnected)).start();
break; // have to break, else it will start 20 threads when the first client connects :P
}
}
}
}
}
SERVER CLIENT CLASS:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class ClientThread extends Thread{
private ClientThread[] clientsConnected;
private Socket socket = null;
private DataInputStream in = null;
private DataOutputStream out = null;
private String clientName = null;
//Constructor
public ClientThread(Socket socket, ClientThread[] clientsConnected){
this.socket = socket;
this.clientsConnected = clientsConnected;
}
public void run(){
try {
// Streams :)
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String message = null;
clientName = in.readUTF();
while (true){
message = in.readUTF();
for (int c = 0; c < clientsConnected.length; c++){
if (clientsConnected[c]!= null && clientsConnected[c].clientName != this.clientName){ //dont send message to your self ;)
clientsConnected[c].sendMessage(message, clientName); // loops through all the list and calls the objects sendMessage method.
}
}
}
} catch (IOException e) {
System.out.println("Client disconnected!");
this.clientsConnected = null;
}
}
// Every instance of this class ( the client ) will have this method.
private void sendMessage(String mess, String name){
try {
out.writeUTF(name + " says: " + mess);
} catch (IOException e) {
e.printStackTrace();
}
}
}
AND FINALLY THE CLIENT:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException {
Main m = new Main();
m.connect();
}
public void connect() throws IOException{
//declare a scanner so we can write a message
Scanner keyboard = new Scanner(System.in);
// localhost ip
String ip = "127.0.0.1";
int port = 4444;
Socket socket = null;
System.out.print("Enter your name: ");
String name = keyboard.nextLine();
try {
//connect
socket = new Socket(ip, port);
//initialize streams
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//start a thread which will start listening for messages
new ReceiveMessage(in).start();
// send the name to the server!
out.writeUTF(name);
while (true){
//Write messages :)
String message = keyboard.nextLine();
out.writeUTF(message);
}
}
catch (IOException e){
e.printStackTrace();
if (!socket.isClosed()){socket.close();}
}
}
class ReceiveMessage extends Thread{
DataInputStream in;
ReceiveMessage(DataInputStream in){
this.in = in;
}
public void run(){
String message;
while (true){
try {
message = in.readUTF();
System.out.println(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I ran the server in eclipse, and started two clients from the CMD, looks like this:
Here is a super simple I made just now with some comments of what is going on. The client connects to the server can can type messages which the server will print out. This is not a chat program since the server receives messages, and the client send them. But hopefully you will understand better it better :)
Server:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static DataInputStream in;
public static DataOutputStream out;
public static void main(String[] args) throws IOException {
int port = 4444;
ServerSocket server = null;
Socket clientSocket = null;
try {
//start listening on port
server = new ServerSocket(port);
System.out.println("Listening on port: " + port);
//Accept client
clientSocket = server.accept();
System.out.println("client Connected!");
//initialize streams so we can send message
in = new DataInputStream(clientSocket.getInputStream());
out = new DataOutputStream(clientSocket.getOutputStream());
String message = null;
while (true) {
// as soon as a message is being received, print it out!
message = in.readUTF();
System.out.println(message);
}
}
catch (IOException e){
e.printStackTrace();
if (!server.isClosed()){server.close();}
if (!clientSocket.isClosed()){clientSocket.close();}
}
}
}
Client:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException {
//declare a scanner so we can write a message
Scanner keyboard = new Scanner(System.in);
// localhost ip
String ip = "127.0.0.1";
int port = 4444;
Socket socket = null;
try {
//connect
socket = new Socket(ip, port);
//initialize streams
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
while (true){
System.out.print("\nMessage to server: ");
//Write a message :)
String message = keyboard.nextLine();
//Send it to the server which will just print it out
out.writeUTF(message);
}
}
catch (IOException e){
e.printStackTrace();
if (!socket.isClosed()){socket.close();}
}
}
}

DNS Interpreter through EchoClient

I have been trying to play around with Java's Socket class and I have hit a tough spot. I have three classes: EchoServerTemplate, ConcurrentServer, and EchoClient.
I want to send a website(www.google.com) from a client to the server and then have the server return the IP address. I think I am extremely close, but I do not know how BufferedStreamer in Java works well enough to figure out the error messages.
Here is my code for all three classes:
EchoServerTemplate (This is where I want the Web Address to be translated):
import java.net.*;
import java.io.*;
public class EchoServerTemplate extends Thread
{
public static final int DEFAULT_PORT = 6007;
public static final int BUFFER_SIZE = 256;
Socket clientSocket;
EchoServerTemplate(Socket cs){
clientSocket = cs;
}
public void run(){
InputStream fromClient = null;
OutputStream toClient = null;
byte[] buffer = new byte[BUFFER_SIZE];
String printaddress = null;
try {
while(true){
PrintWriter pout = new PrintWriter(clientSocket.getOutputStream(), true);
fromClient = new BufferedInputStream(clientSocket.getInputStream());
try {
InetAddress address = InetAddress.getByName(fromClient.toString());
printaddress = address.toString();
}
catch(UnknownHostException e){
System.out.println(e);
}
toClient = new BufferedOutputStream(clientSocket.getOutputStream());
while (printaddress != null) {
toClient.write(printaddress.getBytes("UTF-8"));
toClient.flush();
printaddress = null;
}
fromClient.close();
toClient.close();
clientSocket.close();
}
}
catch (IOException ioe) {
ioe.printStackTrace();}
}
}
ConcurrentServer:
import java.io.*;
import java.net.*;
public class ConcurrentServer {
public static final int BUFFER_SIZE = 256;
public static void main(String[] args) throws IOException {
try {
int serverPortNumber = 6007;
ServerSocket sock = new ServerSocket(serverPortNumber);
while (true) {
Socket clientSocket = sock.accept();
EchoServerTemplate thread = new EchoServerTemplate(clientSocket);
thread.start();
}
}
catch (IOException ioe) {
ioe.printStackTrace();}
}
}
EchoClient:
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("127.0.0.1", 6007);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: ");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to the host.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("IP Address: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
The task I accomplished before this was just having the ConcurrentServer repeat what was typed on the client. In modifying the code I may have accidentally messed something up. Here are the error messages I am receiving:
run: www.google.com Exception in thread "main"
java.net.SocketException: Connection reset at
java.net.SocketInputStream.read(SocketInputStream.java:189) at
java.net.SocketInputStream.read(SocketInputStream.java:121) at
sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283) at
sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325) at
sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177) at
java.io.InputStreamReader.read(InputStreamReader.java:184) at
java.io.BufferedReader.fill(BufferedReader.java:154) at
java.io.BufferedReader.readLine(BufferedReader.java:317) at
java.io.BufferedReader.readLine(BufferedReader.java:382) at
EchoClient.main(EchoClient.java:31) Java Result: 1 BUILD SUCCESSFUL
(total time: 4 seconds)
Any help is appreciated. If you need any more information, please let me know.

Categories

Resources