Connection reset at read() - java

I am trying to implement a server and client based on the web socket technologie but when I run the TCPDataServer class I am getting the following error:
java.io.IOException: connection reset
at java.io.DataInputStream.read(Unknown Source)
at org.server.ClientWorker.run(TCPDataServer.java:67)
at java.lang.Thread.run(Unknown Source)
I excepted to get the following output Hello, I am Alex!
TCPDataClient
package org.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPDataClient {
public static void main(String[] args) {
try {
TCPDataClient obj = new TCPDataClient();
Socket obj_client = new Socket(InetAddress.getByName("127.0.1"), 1000);
DataInputStream din = new DataInputStream(obj_client.getInputStream());
DataOutputStream dout = new DataOutputStream(obj_client.getOutputStream());
byte[] buffer = obj.createDataPacket("Hello, I am Alex!".getBytes("UTF8"));
dout.write(buffer);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private byte[] createDataPacket(byte[] data) {
byte[] packet = null;
try {
byte[] initialize = new byte[1];
initialize[0] = 2;
byte[] separator = new byte[1];
separator[0] = 4;
byte[] data_length = String.valueOf(data.length).getBytes("UIF8");
packet = new byte[initialize.length + separator.length + data_length.length + data.length];
System.arraycopy(initialize, 0, packet, 0, initialize.length);
System.arraycopy(data_length, 0, packet, initialize.length, data_length.length);
System.arraycopy(separator, 0, packet, initialize.length + data_length.length, separator.length);
System.arraycopy(data, 0, packet, initialize.length + data_length.length + separator.length, data.length);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return packet;
}
}
TCPDataServer
package org.server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.logging.Level;
import com.sun.istack.internal.logging.Logger;
public class TCPDataServer {
public static void main(String[] args) {
try {
ServerSocket server_socket = new ServerSocket(1000);
while (true) {
new Thread(new ClientWorker(server_socket.accept())).start();
}
} catch (IOException e) {
System.err.println("Error");
System.err.println(e);
System.err.println("\n2");
System.err.println(e.getMessage());
System.err.println("\n3");
System.err.println(e.getLocalizedMessage());
System.err.println("\n4");
System.err.println(e.getCause());
System.err.println("\n5");
System.err.println(Arrays.toString(e.getStackTrace()));
System.err.println("\n6");
e.printStackTrace();
}
}
}
class ClientWorker implements Runnable {
private Socket target_socket;
private DataInputStream din;
private DataOutputStream dout;
public ClientWorker(Socket recv_scket) {
try {
target_socket = recv_scket;
din = new DataInputStream(target_socket.getInputStream());
dout = new DataOutputStream(target_socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
byte[] initilize = new byte[1];
try {
din.read(initilize, 0, initilize.length);
if (initilize[0] == 2) {
//This is line 67.
System.out.println(new String(readStream()));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private byte[] readStream() {
byte[] data_buff = null;
try {
int b = 0;
String buff_length = "";
while ((b = din.read()) != 4) {
buff_length += (char) b;
}
int data_length = Integer.parseInt(buff_length);
data_buff = new byte[Integer.parseInt(buff_length)];
int byte_read = 0;
int byte_offset = 0;
while (byte_offset < data_length) {
byte_read = din.read(data_buff, byte_read, data_length - byte_offset);
byte_offset += byte_read;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data_buff;
}
}

In your Server program you have used din as your input stream reader which reads from the socket.
In your Client program you have used dout as output stream writer which writes to the underlying socket
In your ClientWorker class you have given multiple read operations using dinfrom the socket, whereas you have given only one write operation to the stream using dout object.
The din object will be blocking/waiting to receive the data from client side, but unfortunately you would have closed (program ends) your socket connection on your client which is reason for the DataInputStream to throw IOException.
And your din object will throw an IO error if your underlying socket/stream has been close and yet you are trying read using it.
Try to maintain the same number of reads and writes on either side (client/server).

You aren't closing the sockets, so your OS is resetting them when the JVM exits.

Related

It duplicates content when transferring it via java socket

I have written a client-socket "system" that is supposed to upload a file.
Although, when I attempt to upload, content duplicates.
I'm pretty sure that it is because the program doesn't recognise the eof.
I've found something like "Object stream", but I don't fancy importing new classes. I reckon that I don't really require that. But I wanna know how what the problem precisely is and how to hanle it.
package client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private Socket socket;
private DataInputStream in;
private DataOutputStream out;
public static void main(String[] args) {
new Client();
}
public Client()
{
try {
socket = new Socket("127.0.0.1", 5010);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
this.sendFile("./some.txt");
in.close();
out.close();
socket.close();
}
catch(UnknownHostException ex)
{
System.out.println("unknown host");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendFile(String path)
{
int bytes = 0;
File file = new File(path);
FileInputStream input;
try {
input = new FileInputStream(file);
long size = file.length();
//long size = file.getTotalSpace();
System.out.println(size);
// send a file's size
out.writeLong(size);
byte[] buffer = new byte[1024];
int i = 0, r=0;
//while((bytes = input.read(buffer,0,buffer.length))!=-1)
while(size > 0 && (bytes = input.read(buffer,0,(int)Math.min(buffer.length, size)))!=-1)
{
System.out.println("\n -------------"+(++i));
for (byte b : buffer)
try
{
if ((char)b == '\n' || r == 0)
System.out.print("\n" + (++r));
System.out.print((char)b);
}
catch(NullPointerException ex)
{
}
out.write(buffer, 0, bytes);
out.flush();
size -= bytes;
}
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket ss;
private Socket cs;
private DataInputStream in;
private DataOutputStream out;
public static void main(String[] args) {
new Server();
}
public Server()
{
try {
ss = new ServerSocket(5010);
cs = ss.accept();
in = new DataInputStream(cs.getInputStream());
out = new DataOutputStream(cs.getOutputStream());
this.receiveFile("./uploaded.txt");
in.close();
out.close();
cs.close();
ss.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
private void receiveFile(String path)
{
int bytes = 0;
try {
File file = new File(path);
file.createNewFile();
FileOutputStream output = new FileOutputStream(file);
long size = in.readLong();
byte[] buffer = new byte[1024];
int i = 0;
while(size>0 && (bytes = in.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1)
{
System.out.println("\n -------------"+(++i));
for (byte b : buffer)
try
{
System.out.print((char)b);
}
catch(NullPointerException ex)
{
}
output.write(buffer, 0, bytes);
size -= bytes;
}
output.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The problem was that I didn't check if the size were 0 on the client side.
That try catch should NOT be in the for loop !!!! It only needs single code use by wrapping. Also use counting metering conventionally the number of bytes with a conventional numeric "for" loop, Not for(byte b : buffer). Note: byte is not strictly numeric, it will only reach to 255 in the for counter! It depends the quantity bytes required iterated over and should be as many as are packaged to it over the connection.
In the read you need to obtain the number of bytes sent andmark that into the write length to take from the array, so it would be better to instantiate the array based on the number of bytes or maximum bytes the the client sender has sent or negotiated as the maximum allowed (see the api docs for the stream.
NB ObjectStream does not apply , it's for RMI)
Of counting into the byte[] buffer array, you should remove it from the method and put it as a global. In the method , instantiate a new "buffer" array on the global variable each iteration of the loop according to the number of bytes read as it's new length.
The code does not appear to be particularly safe or debugable. You might try carefully constructing it starting again from scratch.

DataOutputStream works only preceded by System.out.println

I got another problem with input/output streams. Here i'm sending data from a server to a client. Before sending the data, the server send a little string just to say to the client what he'll send, and so the client know which function he should use to receive.
I'm receiving the first string well, but then i don't get the good integer and after that the second string i receive is "null".
Moreover, if i do a System.out.println before using the DataOutputStream with dos.writeInt, then everything works well.
I dont get it. here's the code:
Server:
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.SecureRandom;
public class Server {
private static OutputStream out;
static byte[] generateRandomBytes(int len) {
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[len];
random.nextBytes(bytes);
return bytes;
}
public static void sendType(String type) {
PrintWriter textWriter = new PrintWriter(out);
textWriter.println(type);
textWriter.flush();
}
public static void sendKeyNumber(int keyNumber) {
sendType("keyNumber");
try {
DataOutputStream dos = new DataOutputStream(out);
//System.out.println("Sending key number: " + keyNumber);
dos.writeInt(keyNumber);
//dos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void sendKey(byte[] key) {
sendType("key");
try {
DataOutputStream dos = new DataOutputStream(out);
//System.out.println("key length to send: " +key.length);
dos.writeInt(key.length); // write length of the byte array
//dos.flush();
dos.write(key);
//dos.flush();
System.out.println("key send: " +key);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket clientSocket ;
System.out.println("ouverture du server");
try {
ServerSocket serverSocket = new ServerSocket(2004);
clientSocket = serverSocket.accept();
out = clientSocket.getOutputStream();
sendKeyNumber(0);
byte[] keyBytes = generateRandomBytes(32);
sendKey(keyBytes);
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.crypto.spec.SecretKeySpec;
public class Main {
static InputStream in;
public static int receiveKeyNumber() {
DataInputStream dis = new DataInputStream(in);
int keyNumber = 0;
try {
keyNumber = dis.readInt();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return keyNumber;
}
public static SecretKeySpec receiveKey() {
DataInputStream dIn = new DataInputStream(in);
int length;
byte[] keyBytes = null;
try {
length = dIn.readInt(); // read length of incoming message
System.out.println("key length: " + length);
if(length!=32) {
System.err.println("Incorrect size for key: "+ length);
}
else {
keyBytes = new byte[length];
dIn.readFully(keyBytes, 0, keyBytes.length);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SecretKeySpec aesKey = new SecretKeySpec(keyBytes, "AES");
return aesKey;
}
public static void main(String[] args) {
Socket clientSocket;
try {
clientSocket = new Socket(InetAddress.getLocalHost(),2004);
in = clientSocket.getInputStream();
while(!clientSocket.isClosed()) {
BufferedReader textReader = new BufferedReader(new InputStreamReader(in));
String type = textReader.readLine();
System.out.println(type);
if(type.equals("keyNumber")) {
int KN = receiveKeyNumber();
System.out.println(KN);
}
if(type.equals("key")) {
SecretKeySpec key = receiveKey();
System.out.println(key);
}
}
clientSocket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
End here's what i get (in Client console) when i don't do the System.out.println:
keyNumber
1801812234
null
I always get the same weird number; i've try to convert it to ASCII, but it's not readable.
Any suggestion?
In this case where binary data is sent, go entirely for DataOutputStream.
(Alternatively you could go for text.)
private static DataOutputStream out;
out = new DataOutputStream(clientSocket.getOutputStream());
public static void sendType(String type) {
out.writeUTF(type);
out.flush();
}
Flushing is important with binary conversations.
The problem with wrapping classes DataOutputStream, Printer, BufferedReader and such is that they start their own "cursor" and would close the wrapped I/O on their own closing. Having several DataOutputStreams is somewhat worrying; at least not as intended.
By the way my normal pattern is to do in main: new Server().exec(); or such.
That would remove all those statics.

Java multi client chat server

I am new to Java programming and am trying to develop multi-client chat server.
following is my code:
package Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
public class server implements Runnable{
private List<ServerClient> clients = new ArrayList<ServerClient>();
//private String UID;
private int port;
private ServerSocket socket;
private Thread run, manage, send, receive;
private boolean running = false;
public int i=0;
public server(int port){
// this.UID = UID;
this.port = port;
try {
socket = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
run = new Thread(this, "Server");
run.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
running = true;
ManageClients();
receive();
}
private void ManageClients(){
manage = new Thread("Manage"){
public void run(){
while(running){
//managing
}
}
};
manage.start();
}
private void receive(){
receive = new Thread("Receive"){
public void run(){
Socket S1 = null;
try {
S1 = socket.accept();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(running){
/* byte [] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String string = new String(packet.getData());
System.out.println(string);*/
/* BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(S1.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String string = br.readLine();
System.out.println(string);
process(string);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
process(S1);
System.out.println(String.valueOf(i));
i++;
}
}
};
receive.start();
}
private void process(Socket S1){
BufferedReader br = null;
String string = "";
try {
br = new BufferedReader(new InputStreamReader(S1.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
string = br.readLine();
System.out.println(string);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(string.startsWith("/c/")){
clients.add(new ServerClient("name", S1.getInetAddress(), S1.getPort(), "UID"));
}
else if(string.startsWith("/ip/")){
//send ip address to raspberry
System.out.println(string);
}
else if(string.startsWith("/r/")){
//send relay command to relay
System.out.println(string);
}
}
}
The server is accepting only one connection. If I try to connect another user the console does not show any output.
Can you please guide where I am going wrong.
Thank you
You need to run the accept method multiple times... once for each client that wants to connect. Typically people do that on a separate thread in a while loop since the accept method is blocking.
In your code it seems like you are only calling accept once, and hence you will only get one client connection.
I would recommend that you change your code architecture here, but if you want to keep it the same, and you know how many clients will connect, then you could wrap your access to socket in a synchronization lock, and call your receive method once for each client.

Why does my TCP connection close after running a command? - Java

I have a simple FTP server and client. For now, the client can send a file, and the server can accept it, but after i run a sendFile() command, it transfers the file, and the server and the client terminate, making it unable to run any other commands after that.
SERVER
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import mmd.filetransfer.FileEvent;
public class Server {
private ServerSocket serverSocket = null;
private Socket socket = null;
private ObjectInputStream inputStream = null;
private FileEvent fileEvent;
private File dstFile = null;
private FileOutputStream fileOutputStream = null;
public Server() {
}
/**
  * Accepts socket connection
  */
public void doConnect() {
try {
serverSocket = new ServerSocket(4445);
socket = serverSocket.accept();
inputStream = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
  * Reading the FileEvent object and copying the file to disk.
  */
public void downloadFile() {
try {
fileEvent = (FileEvent) inputStream.readObject();
if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
System.out.println("Error occurred ..So exiting");
System.exit(0);
}
String outputFile = fileEvent.getDestinationDirectory() + fileEvent.getFilename();
if (!new File(fileEvent.getDestinationDirectory()).exists()) {
new File(fileEvent.getDestinationDirectory()).mkdirs();
}
dstFile = new File(outputFile);
fileOutputStream = new FileOutputStream(dstFile);
fileOutputStream.write(fileEvent.getFileData());
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("Output file : " + outputFile + " is successfully saved ");
//Thread.sleep(0);
//System.exit(0);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.doConnect();
server.downloadFile();
}
}
CLIENT
package mmd.client;
import java.io.*;
import java.net.Socket;
import mmd.filetransfer.FileEvent;
public class Client {
private Socket socket = null;
private ObjectOutputStream outputStream = null;
private boolean isConnected = false;
private String sourceFilePath = "/home/jovan/Desktop/videot.mpg";
private FileEvent fileEvent = null;
private String destinationPath = "/home/jovan/Desktop/tp/";
public Client() {
}
/**
  * Connect with server code running in local host or in any other host
  */
public void connect() {
while (!isConnected) {
try {
socket = new Socket("localHost", 4445);
outputStream = new ObjectOutputStream(socket.getOutputStream());
isConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendFile() {
fileEvent = new FileEvent();
String fileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1, sourceFilePath.length());
String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
fileEvent.setDestinationDirectory(destinationPath);
fileEvent.setFilename(fileName);
fileEvent.setSourceDirectory(sourceFilePath);
File file = new File(sourceFilePath);
if (file.isFile()) {
try {
DataInputStream diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
fileBytes.length - read)) >= 0) {
read = read + numRead;
}
fileEvent.setFileSize(len);
fileEvent.setFileData(fileBytes);
fileEvent.setStatus("Success");
} catch (Exception e) {
e.printStackTrace();
fileEvent.setStatus("Error");
}
} else {
System.out.println("path specified is not pointing to a file");
fileEvent.setStatus("Error");
}
//Now writing the FileEvent object to socket
try {
outputStream.writeObject(fileEvent);
System.out.println("Done...Going to exit");
Thread.sleep(0);
//System.exit(0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
  * Sending FileEvent object.
 
* #throws IOException */
public static void main(String[] args){
Client client = new Client();
client.connect();
client.sendFile();
client.sendFile();
}
}
How to prevent this?
Calling it an FTP server is a bit confusing, as this does not implement RFC 959.
Your main() in the server code does not have any loop. It just listens, transfers one file and exits. Put it in an infinite loop as ravindra suggests.

Client - Server : How to Let Server send the received message to another client instead of sending it back to original client?

I am trying to code a chat in my java software,
i have 2 eclipses running on my windows 7.
one of the eclipses includes a project "ServerListener" which contains a class Server.java
and the other eclipse includes a project "Client" and contains a class cl.java.
I am sending messages from my cl.java to the server.java
each time the server receives a message he send it back to the cl.java (the one i sent the message from) to make sure it's connected.
(THIS PART WORKS FINE sending message to the server and back from the server to the same client)
my question is :
how to let the server.java send the message to another client instead of the original client?
if i run another eclipse with the same project as "Client"
i want to the two eclipses to chat together
this is the Server.java:
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
ServerSocket serverSocket;
ArrayList<ServerThread> allClients = new ArrayList<ServerThread>();
public static void main(String[] args) {
new Server();
}
public Server() {
// ServerSocket is only opened once !!!
try {
serverSocket = new ServerSocket(6000);
System.out.println("Waiting on port 6000...");
boolean connected = true;
// this method will block until a client will call me
while (connected) {
Socket singleClient = serverSocket.accept();
// add to the list
ServerThread myThread = new ServerThread(singleClient);
allClients.add(myThread);
myThread.start();
}
// here we also close the main server socket
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class ServerThread extends Thread {
Socket threadSocket;
String msg;
boolean isClientConnected;
InputStream input;
ObjectInputStream ois;
OutputStream output;
ObjectOutputStream oos; // ObjectOutputStream
public ServerThread(Socket s) {
threadSocket = s;
}
public void sendText(String text) {
try {
oos.writeObject(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
input = threadSocket.getInputStream();
ois = new ObjectInputStream(input);
output = threadSocket.getOutputStream();
oos = new ObjectOutputStream(output);
// get the user name from the client and store
// it inside thread class for later use
//msg = (String) ois.readObject();
isClientConnected = true;
//System.out.println(msg);
for(ServerThread t:allClients)
t.sendText("User has connected...");
// send this information to all users
// dos.writeUTF(userName + " has connected..");
// for(ServerThread t:allClients)
// t.sendText(msg);
while (isClientConnected) {
System.out.println("connect ... ");
try {
msg = (String) ois.readObject();
System.out.println(msg);
if (msg.equals("quit"))
break;
for (ServerThread t : allClients)
t.sendText(msg);
} catch (Exception e) {
}
}
// close all resources (streams and sockets)
ois.close();
oos.close();
threadSocket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
this is the client (cl.java):
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class cl {
public static final String HOST = "127.0.0.1";
public static final int PORT = 6000;
static ConnectThread clientThread;
boolean isConnected;
static boolean isOnline = false;
static Scanner scanner = new Scanner(System.in);
static String msg;
public static void main(String[] args) {
new cl();
}
public cl() {
connectUser();
}
public void connectUser() {
clientThread = new ConnectThread();
clientThread.start();
}
class ConnectThread extends Thread {
InputStream input;
OutputStream output;
ObjectOutputStream oos;
Socket s;
public void sendText(String text) {
try {
System.out.println("sending text to server..");
oos.writeObject(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
s = new Socket(HOST, PORT);
output = s.getOutputStream();
oos = new ObjectOutputStream(output);
isOnline = true;
isConnected = true;
new ListenThread(s).start();
while (isOnline) {
System.out.println("Enter a Text to send:");
msg = scanner.nextLine();
clientThread.sendText("amjad: " + msg);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ListenThread extends Thread {
Socket s;
InputStream input;
ObjectInputStream ois;
public ListenThread(Socket s) {
this.s = s;
try {
input = s.getInputStream();
ois = new ObjectInputStream(input);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
while (isConnected) {
try {
final String inputMessage = (String) ois.readObject();
System.out.println(inputMessage);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
thanks in advance

Categories

Resources