I'm writing a Client-Server chat application. I can connect them and I can send-receive the first message. But I can't send the second one. I tried to add the do...while() statement for a repetition but It doesn't work. Could some one help me to resolve this problem? Many thanks
This is my server class
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(4999);
Socket serverSocket = server.accept();
System.out.println("client is connected");
String messIn = "", messOut = "";
InputStreamReader serverInput = new InputStreamReader(serverSocket.getInputStream());
BufferedReader serverBufIn = new BufferedReader(serverInput);
Scanner serverScanner = new Scanner(System.in);
PrintWriter serverWriter = new PrintWriter(serverSocket.getOutputStream());
do {
messIn = serverBufIn.readLine();
System.out.println("client : " + messIn);
messOut = serverScanner.nextLine();
serverWriter.print(messOut);
serverWriter.flush();
} while (messOut.equals("quit"));
serverSocket.close();
serverWriter.close();
}
}`
This my client class
`import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class client {
public static void main(String[] args) throws IOException {
Socket clientSocket = new Socket(InetAddress.getLocalHost(), 4999);
System.out.println("You are connected. Say something!");
String messIn = "", messOut = "";
InputStreamReader clientInput = new InputStreamReader(clientSocket.getInputStream());
BufferedReader clientBufIn = new BufferedReader(clientInput);
Scanner clientScanner = new Scanner(System.in);
PrintWriter clientWriter = new PrintWriter(clientSocket.getOutputStream());
do {
messOut = clientScanner.nextLine();
clientWriter.println(messOut);
clientWriter.flush();
messIn = clientBufIn.readLine();
System.out.println("server : " + messIn);
} while (messOut.equals("quit"));
clientSocket.close();
clientWriter.close();
}
}
`
try while (true) { }
my code:
public static void newSocket(int port) throws IOException {
ServerSocket ss = new ServerSocket(port);
while (run) {
try {
final Socket socket = ss.accept();
new Thread() {
public void run() {
try {
while (true) {
int i = socket.getInputStream().available();
if (i > 0) {
byte[] bytes = new byte[i];
socket.getInputStream().read(bytes, 0, i);
String s = new String(bytes);
String[] split = s.split("\\|");
if (split.length > 1) {
if (split[0].equals("hello")) {
String msg = split[1];
System.out.println(msg);
PrintStream p = new PrintStream(socket.getOutputStream());
p.println("hello back");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
} catch (Exception e) {
e.printStackTrace();
}
}
ss.close();
}
Related
as I said, i'm tring to do a chat for sevral clients, and one server in java. However, it seems that only one client at the time can connect on the server, and I really don't know why (i'm a begginer in this field).
I have 4 classes, here are they :
MainClient :
package Multicast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class MainClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000)){
BufferedReader input = new BufferedReader(new java.io.InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
String userInput;
String reponse;
String clientName = "none";
ClientThread clientThread = new ClientThread(socket);
clientThread.start();
do {
if(clientName.equals("none")) {
System.out.println("please enter your name");
userInput = scanner.nextLine();
clientName = userInput;
output.println(userInput);
}
else {
String message = ("|"+clientName +"| :");
//System.out.println(message);
userInput = scanner.nextLine();
output.println(message + " " + userInput);
if (userInput.equals("exit")) {
break;
}
}
}while (!userInput.equals("exit"));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ClientThread :
package Multicast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ClientThread extends Thread{
private Socket socket;
private BufferedReader input;
public ClientThread(Socket s) throws IOException {
this.socket = s;
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
#Override
public void run() {
try {
while(true) {
String reponse = input.readLine();
System.out.println(reponse);
}
}
catch(IOException e){
e.printStackTrace();
}
finally {
try {
input.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
MainServer :
package Multicast;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class MainServeur {
public static void main(String[] args) {
ArrayList<ServerThread> threadList = new ArrayList<>();
try(ServerSocket serverSocket = new ServerSocket(5000)){
Socket socket = serverSocket.accept();
ServerThread serverThread= new ServerThread(socket, threadList);
threadList.add(serverThread);
serverThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and ServerThread :
package Multicast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ServerThread extends Thread{
private Socket socket;
private ArrayList<ServerThread> threadList;
private PrintWriter output;
public ServerThread(Socket socket, ArrayList<ServerThread> threads) {
this.socket = socket;
this.threadList = threads;
}
#Override
public void run() {
try {
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(), true);
while(true) {
String outputString = input.readLine();
if(outputString.equals("exit")) {
break;
}
printToAllClients(outputString);
System.out.println("Server received : " + outputString);
}
}
catch(Exception e) {
System.out.println("error occured in main of server : "+ e.getStackTrace());
}
}
private void printToAllClients(String outputString) {
for(ServerThread sT : threadList) {
sT.output.println(outputString);
}
}
}
when i try to connect a second client, this error occurs :
java.net.BindException: Cannot assign requested address: connect
at java.base/sun.nio.ch.Net.connect0(Native Method)
at java.base/sun.nio.ch.Net.connect(Net.java:579)
at java.base/sun.nio.ch.Net.connect(Net.java:568)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
at java.base/java.net.Socket.connect(Socket.java:633)
at java.base/java.net.Socket.connect(Socket.java:583)
at java.base/java.net.Socket.<init>(Socket.java:507)
at java.base/java.net.Socket.<init>(Socket.java:287)
at Multicast.MainClient.main(MainClient.java:13)
I followed this tutorial, thanks a lot and sorry if the post is too long.
Edit : My problem is solved, here are the changes :
package Multicast;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class MainServeur {
public static void main(String[] args) {
ArrayList<ServerThread> MyThread = new ArrayList<>();
try (ServerSocket serverSocket = new ServerSocket(5000)) {
for (;;) {
Socket socket = serverSocket.accept();
ServerThread s = new ServerThread(socket, MyThread);
MyThread.add(s);
s.start();
}
} catch (IOException e) {
e.printStackTrace();;
}
}
}
You should have one ServerSocket that accepts one client after another in a loop,
on the specified port 5000.
The session then is handled in an other thread, so the next client can be accepted (waited upon).
public class MainServeur {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(5000)) {
for (;;) {
Socket socket = serverSocket.accept();
new ServerThread(socket).start();
}
} catch (IOException e) {
System.getLogger(MainServeur.class.getName()).error(e);
}
}
}
Rather than elementary using a Thread, you can use ExecutorServices.
ThreadPoolExecutor executor = (ThreadPoolExecutor) executors.newFixedThreadPool(50);
That goes beyond the question asked, but allows thread pools limiting the number of clients, wait for all threads to end and more.
i'm developing a Java App, but i have a big problem. I'm trying to develop a client-server app, so that the client could retrieve information managed by a server.
The problem is that, when the connection is established, probably goes in loop, near two specifics lines of code (cause if i delete this lines, it goes on):
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
I'm an University Student and the client.java has been delivered by professor, so i do not think that this could have problem, but you never know. Now i post 3 files:
MultiServer: used to manage multiclients connection
ServerOneClient: to implements the protocol
Client.java
package server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import com.mysql.cj.xdevapi.Client;
public class MultiServer {
private int PORT = 2025;
private void run() throws IOException
{
ServerSocket serverSocket = new ServerSocket(PORT);
Socket clientSocket = null;
BufferedReader in=null;
PrintWriter out=null;
try {
clientSocket = serverSocket.accept();
System.out.println("Connection Accepted");
//stream di input
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
in = new BufferedReader(isr);
//creazione stream di output
OutputStreamWriter osw = new OutputStreamWriter(clientSocket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, true);
//ciclo di ricezione dal client e invio risposta
while(true)
{
String str = in.readLine();
if(str.equals("END")) break;
System.out.println("Echoing: " + str);
out.println(str);
}
}
catch (IOException e)
{
System.err.println("Accept failed");
System.exit(1);
}
//chiusura di stream e socket
System.out.println("Echoserver: closing..");
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
public MultiServer(int port) throws IOException {
PORT=port;
run();
}
public static void main(String[] args) throws IOException
{
MultiServer s = new MultiServer(2025);
s.run();
}
}
ServerOneClient.java
package server;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerOneClient extends Thread {
private Socket socket;
private ObjectInputStream in;
private ObjectOutputStream out;
public ServerOneClient(Socket s) throws IOException {
socket = s;
in = new ObjectInputStream(s.getInputStream());
out = new ObjectOutputStream(s.getOutputStream());
start();
}
public void run()
{
super.run();
}
}
Client.java
package client;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import utility.Keyboard;
public class Client {
private Socket socket=null;
private ObjectOutputStream out=null;
private ObjectInputStream in=null;
/**
* #param args
* #throws IOException
* #throws ClassNotFoundException
*/
Client (String address, int port) throws IOException, ClassNotFoundException{
socket = new Socket(address, port);
System.out.println(socket);
talking();
}
private void talking() throws IOException, ClassNotFoundException {
int decision=0;
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream()); // stream con richieste del client
String menu="";
do {
do{
System.out.println("Load KNN from file [1]");
System.out.println("Load KNN from binary file [2]");
System.out.println("Load KNN from database [3]");
decision=Keyboard.readInt();
}while(decision <0 || decision >3);
String risposta="";
do {
out.writeObject(decision);
String tableName="";
System.out.println("Table name (without estensione):");
tableName=Keyboard.readString();
out.writeObject(tableName);
risposta=(String)in.readObject();
}while(risposta.contains("#ERROR"));
System.out.println("KNN loaded on the server");
// predict
String c;
do {
out.writeObject(4);
boolean flag=true; //reading example
do {
risposta=(String)(in.readObject());
if(!risposta.contains("#ENDEXAMPLE")) {
// sto leggendo l'esempio
String msg=(String)(in.readObject());
if(risposta.equals("#READSTRING")) //leggo una stringa
{
System.out.println(msg);
out.writeObject(Keyboard.readString());
}
else //leggo un numero
{
double x=0.0;
do {
System.out.println(msg);
x=Keyboard.readDouble();
}
while(new Double(x).equals(Double.NaN));
out.writeObject(x);
}
}
else flag=false;
}while( flag);
//sto leggendo k
risposta=(String)(in.readObject());
int k=0;
do {
System.out.print(risposta);
k=Keyboard.readInt();
}while (k<1);
out.writeObject(k);
//aspetto la predizione
System.out.println("Prediction:"+in.readObject());
System.out.println("Vuoi ripetere predizione? Y/N");
c=Keyboard.readString();
}while (c.toLowerCase().equals("y"));
System.out.println("Vuoi ripetere una nuova esecuzione con un nuovo oggetto KNN? (Y/N)");
menu=Keyboard.readString();
}
while(menu.toLowerCase().equals("y"));
}
public static void main(String[] args){
InetAddress addr;
try {
addr = InetAddress.getByName("localhost");
} catch (UnknownHostException e) {
System.out.println(e.toString());
return;
}
Client c;
try {
c=new Client("localhost", 2025);
} catch (IOException e) {
System.out.println(e.toString());
return;
} catch (NumberFormatException e) {
System.out.println(e.toString());
return;
} catch (ClassNotFoundException e) {
System.out.println(e.toString());
return;
}
}
}
Hope you can help me, for any doubt, i'm here!
Client-Side Below
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class TCPclient {
public static void openChat() throws UnknownHostException, IOException {
Scanner keyboard = new Scanner(System.in);
boolean exit = false;
while (!exit) {
String input = keyboard.nextLine();
if(input != null) {
if ("quit".equals(input)) {
System.out.println("Exit programm");
exit = true;
} else if ("/".equals(input)) {
//Do something
getInput();
}
}
}
}
public static void getInput() throws UnknownHostException, IOException {
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
sendMessage(message);
openChat();
}
public static void sendMessage(String message) throws UnknownHostException, IOException {
Socket sock = new Socket("localhost", 9999);
InputStream input = sock.getInputStream();
OutputStream output = sock.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
PrintWriter writer = new PrintWriter(output, true);
System.out.println(message);
writer.write(message);
sock.close();
}
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("Type / to chat or quit to exit");
openChat();
}
}
Server side Below
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
class ServiceThread extends Thread {
Socket sock;
public ServiceThread(Socket sock) {
this.sock = sock;
}
public void run() {
try {
InputStream input = sock.getInputStream();
OutputStream output = sock.getOutputStream();
byte request[] = new byte[100];
input.read(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
PrintWriter writer = new PrintWriter(output, true);
String message = reader.readLine();
System.out.println(message);
sock.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class TCPserver {
static ArrayList<ServiceThread> theClients = new ArrayList<ServiceThread>();
public TCPserver() {
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket serSock = new ServerSocket(9999);
while(true) {
Socket sock = serSock.accept();
ServiceThread server = new ServiceThread(sock);
theClients.add(server);
server.start();
}
}
}
I get null returned when I want to get the client's message returned.
I am new to this so tell me if I am just doing this all wrong.
Also I would like to know how to you guys learned this information becuase I want to learn more about this and dont knoow where to learn it.
There are server issues in your implementation.
Inside ServiceThread, the run method closes sock(socket) that's why the connection closed after just staring.
Re-write run :
public void run() {
try {
DataInputStream inputStream = new DataInputStream(sock.getInputStream());
//DataOutputStream output = new DataOutputStream(sock.getOutputStream());
String str=(String)inputStream.readUTF();
System.out.println("Client Echo:" + str);
//sock.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Need to modify client implementation also:
You initialize socket connection inside sendMessage method. So, you failed to communicate with the server. So, initialize socket in the constructor.
Modified TCPclient:
public class TCPclient {
DataOutputStream dataOutputStream = null;
public TCPclient() throws UnknownHostException, IOException {
Socket sock = new Socket("localhost", 9999);
dataOutputStream = new DataOutputStream(sock.getOutputStream());
}
public void sendMessage(String message) throws UnknownHostException, IOException {
System.out.println(message);
dataOutputStream.writeUTF(message);
}
public static void main(String[] args) throws UnknownHostException, IOException {
TCPclient tcPclient = new TCPclient();
System.out.println("Type / to chat or quit to exit");
tcPclient.sendMessage("Hello From Client");
tcPclient.openChat();
}
}
It works for me. Try it. I use DataInputpStream and DataOutputStrem instead of InputStream and OutputStream, these are not major issue.
I'm implementing a simple tcp chat between a server and a client. I'm using multi-threading so as the server and the client can send and receive data at the same time (full duplex). The program works but if the server has a console for both typing the sending message and also displaying receiving message (same case for client), I cannot edit my typed message that should be sent to server or client when a message has been received from the other side. For e.g:
run(server console):
input msg to send client:
you:
client: hi server
client: bye server.
For this example, i've typed a message to send to client while the client has already said hi server bye server. Before receiving from client, i see what i've typed but after receiving, I can't see the msg nor edit it.
I can only use console because im not good with GUI and i want the same console for both sending and receiving data.
The codes for the program are shown below.
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class ThreadServerSend implements Runnable {
String d;
Socket s1 = null;
Scanner sc = new Scanner(System.in);
public ThreadServerSend(Socket s)
{
s1=s;
}
public void run()
{
System.out.println("input msg to send client: ");
while (true){
try{
PrintStream p = new PrintStream(s1.getOutputStream());
System.out.println("you: ");
d=sc.nextLine();
p.println(d);
if (d.charAt(d.length()-1)=='.'){
s1.close();
break;}
}
catch(IOException e){}
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ThreadServerReceive implements Runnable {
String m;
Socket s2 = null;
Scanner sc = new Scanner(System.in);
public ThreadServerReceive(Socket s)
{
s2=s;
}
public void run()
{
while (true){
try{
BufferedReader b = new BufferedReader(new InputStreamReader(s2.getInputStream()));
m = b.readLine();
System.out.println("client: "+m);
if (m.charAt(m.length()-1)=='.'){
s2.close();
break;}}
catch(IOException e){}
}
}
}
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
public static void main(String[] args) throws UnknownHostException, IOException{
// TODO Auto-generated method stub
ServerSocket s = new ServerSocket(444);
Socket s1 = s.accept();
new Thread(new ThreadServerSend(s1)).start();
ServerSocket s4 = new ServerSocket(443);
Socket s2=s4.accept();
new Thread(new ThreadServerReceive(s2)).start();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ThreadClientSend implements Runnable {
String d;
Socket s1 = null;
Scanner sc = new Scanner(System.in);
public ThreadClientSend(Socket s)
{
s1=s;
}
public void run()
{
System.out.println("Input msg to send server: ");
while (true){
try{
PrintStream p = new PrintStream(s1.getOutputStream());
System.out.println("you: ");
String d = new Scanner(System.in).nextLine();
p.println(d);
if (d.charAt(d.length()-1)=='.'){
s1.close();
break;}
}
catch(IOException e){}
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ThreadClientReceive implements Runnable {
String m;
Socket s1 = null;
Scanner sc = new Scanner(System.in);
public ThreadClientReceive (Socket s)
{
s1=s;
}
public void run()
{
while (true){
try{
BufferedReader b = new BufferedReader(new InputStreamReader(s1.getInputStream()));
m= b.readLine();
System.out.println("Server: "+m);
if (m.charAt(m.length()-1)=='.')
{
s1.close();
break;
}
}
catch(IOException e){}
}
}
}
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException{
// TODO Auto-generated method stub
Socket s1= new Socket("localhost",444);
Socket s2 = new Socket("localhost",443);
new Thread(new ThreadClientReceive(s1)).start();
new Thread(new ThreadClientSend(s2)).start();
}
}
A bit late, but I actually came up with a working version of this chat client for my programming class. I thought I might as well post it here. I used TCP (full duplex) with multithreading, and I got it to work in console. The small problem is that you can't see your own name (because console has only one active line), but otherwise it works pretty well.
Server (client is more or less the same, obviously the Sockets are normal sockets, not ServerSockets):
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
#SuppressWarnings("serial")
public class serverProgII extends Thread
{
private static ObjectOutputStream oos;
private static ObjectInputStream ois;
private static Socket connection;
private static ServerSocket server;
private static String ip, clientIP, textin, exitword ="exit";
private static networkmessage nmessage;
private static boolean connected = false;
private static boolean done = false;
private static String myName = "";
private static int counter = 0;
public static boolean started = false;
public String type;
public static void main(String[] args)
{
try {
BufferedReader brin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name:> "); //send prompt to DOS window
myName = brin.readLine(); //read in user input
setupConnection();
setupStreams();
started = true;
} catch (Exception e) {
System.out.println("Problem setting up streams and connection!");
}
serverProgII sender = new serverProgII("sender");
serverProgII receiver = new serverProgII("receiver");
sender.start();
receiver.start();
}
public serverProgII(String t)
{
super();
type = t;
}
public void run() {
while(started) {
switch(type) {
case "sender":
sender();
break;
case "receiver":
receiver();
break;
}
try {
Thread.sleep(500); //milliseconds
} catch(Exception e){}
}
}
/* runServer()
This is where all the actual work gets done.
*/
public void sender()
{
try {
BufferedReader inn = new BufferedReader(new InputStreamReader(System.in));
textin = inn.readLine();
sendData(textin);
if (textin.equals(exitword)) // if "exit" is typed in shutdown the server.
{
started = false;
serverShutdown();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void receiver() {
try {
getData();
} catch(Exception e) {
System.out.println("Error getting data");
}
}
//setup connection
public static void setupConnection() throws IOException
{
System.out.println("SERVER MODE ACTIVATED");
server = new ServerSocket (8000); //create the socket at port 8000
System.out.println("Waiting For Connection...");
connection = server.accept(); //wait for a connection
System.out.println("Received connection: "+connection.getInetAddress());
clientIP=""+connection.getInetAddress(); //print out the client IP address
}//setupconnection()
//Setup streams connection
public static void setupStreams() throws IOException
{
//Open up Streams
System.out.println("Streams Setup");
oos=new ObjectOutputStream(connection.getOutputStream()); //construct object output stream
ois=new ObjectInputStream(connection.getInputStream());
oos.flush();
}//setupStreams()
//method to write/send network data
public void sendData(String toSend) throws IOException
{
try
{
nmessage = new networkmessage(myName, toSend);
oos.writeObject(nmessage);
}//try
catch (IOException ioException)
{
System.out.println("IO exception in sendData");
}
}//sendData()
//method to read in network data
public void getData() throws IOException
{
try
{
networkmessage messageIn =(networkmessage)(ois.readObject());
System.out.println(messageIn.ipnum +" << "+messageIn.text);
}//try
catch (Exception exp1)
{
System.out.println("IO exception in sendData");
}
}//getData()
public void serverShutdown()
{
System.out.println("exiting initiated");
try
{
done = true;
textin = "Chat is terminated. Have a nice day.";
oos.close();
server.close();
connection.close();
}
catch (Exception One)
{
System.out.println("bad termination");
}
}
} // class serverProg
I have received error message after the client side successful received one message from server side. The error message is: Exception in thread "main" java.net.SocketException: Software caused connection abort: recv failed
It seems in client class, line = inFromserver.readLine(); would not receive any message from server, making it become "null". But I dont know why. Could somebody please help me?
Server class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class ConcurrentServer {
public static void main(String args[]) throws IOException
{
int portNumber = 20020;
ServerSocket serverSocket = new ServerSocket(portNumber);
while ( true ) {
new ServerConnection(serverSocket.accept()).start();
}
}
}
class ServerConnection extends Thread
{
Socket clientSocket;
PrintWriter outToClient;
ServerConnection (Socket clientSocket) throws SocketException
{
this.clientSocket = clientSocket;
setPriority(NORM_PRIORITY - 1);
}
public void run()
{
BufferedReader inFromClient;
try{
inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream outToClient = clientSocket.getOutputStream();
PrintWriter printOutPut = new PrintWriter(new OutputStreamWriter(outToClient),true);
String request= inFromClient.readLine();
if(request !=null)
{
if(!request.equalsIgnoreCase("finished"))
{
printOutPut.write("Receving data");
}
else
{
printOutPut.write("file received");
}
}
}catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try
{
clientSocket.close();
}catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
client class
import java.io.*;
import java.net.*;
import java.util.concurrent.TimeUnit;
public class client{
public static void main(String[] args) throws Exception{
final int PORT=20020;
String serverHostname = new String("127.0.0.1");
Socket socket;
PrintWriter outToServer;
BufferedReader inFromServer;
BufferedReader inFromUser;
byte[] dataToTransfer;
String line;
int counter=0;
int i=0;
socket = new Socket(serverHostname, PORT);
outToServer = new PrintWriter(socket.getOutputStream(),true);
inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
inFromUser = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Simulation of file transferring");
System.out.println("Enter the file size you want to transfer (Max Size 50MB)");
int userInput = Integer.parseInt(inFromUser.readLine());
System.out.println("Transferring start");
boolean connection = true;
while(connection)
{
//set transfer rate at 1MB/s
dataToTransfer = new byte[1000000];
Thread.sleep(1000);
if(i<userInput)
{
outToServer.println(dataToTransfer);
counter++;
System.out.println(counter + "MB file has been transferred");
}
else
{
outToServer.println("Finished");
}
line = inFromServer.readLine();
System.out.println(line);
if(!line.equalsIgnoreCase("file received"))
{
}
else
{
System.out.println("Transfer completed");
break;
}
i++;
}
outToServer.close();
inFromServer.close();
inFromUser.close();
socket.close();
}
}
You are sending byte array from client to server and reading string on server side.
Insert somthing in your byte array and then Convert your byte array into String
String str = new String(dataToTransfer,int offset, 1000000);
then write:
outToServer.println(str);