TCP socket communication failed after the first trial - java

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);

Related

Thread Pooled Concurrent Server (JAVA)

This is my 2nd ever Post I'm pretty new to Programming.
I'm working on making my Socket Server Concurrent (Multithreaded) on the Server side. I understand I have to use Threaded Pools after my Socket accepts but I'm just very confused what to do. currently the requests are slower then it was when it was only iterative because its not working correctly.
//MultiClient Class
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.net.*;
import java.io.*;
public class MultiServer {
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
System.out.println("What port should the server be using?");
int portNumber = scnr.nextInt();
while ((portNumber < 1025) ||(portNumber > 4998)) {
System.out.println("Please enter a Port Number between '1025' and '4998'.");
portNumber = scnr.nextInt();
}
try (ServerSocket serverSock = new ServerSocket(portNumber)){
System.out.println("Server listening on port " + portNumber);
while(true) {
Socket sock = serverSock.accept();
MultiServerHandler msh = new MultiServerHandler(sock);
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
executor.execute(msh);
}
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();
}
}
}
//MultiClientHandler Class
import java.io.*;
import java.net.*;
public class MultiServerHandler extends Thread{
private Socket sock;
public MultiServerHandler(Socket sock) {
this.sock = sock;
}
public void run() {
try {
System.out.println("New client connected");
InputStream input = sock.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = sock.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
String command;
command = reader.readLine();
Process process = Runtime.getRuntime().exec(command);
BufferedReader read = new BufferedReader(new InputStreamReader(process.getInputStream()));
String result;
while((result = read.readLine()) != null) {
writer.println(result);
}
sock.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
So far I just know I have to implement it after the socket accepts but I'm not too sure yet.

java.net.SocketException Error. What am I doing wrong?

I created a SOA service with Socket Adapter on JDeveloper and I need to run/test it using Java. So I created a server class and a client class but I am getting an error
I did some research on how to create this service and test it and I came across some helpful material online but yet I'm getting an error and I dont know how to fix it. I am very new to making socket servers and stuff.
here is my server class
package client;
import java.net.ServerSocket;
import java.net.Socket;
public class Class1 {
try {
ServerSocket socket = new ServerSocket(12110);
Socket s=socket.accept();
System.out.println("Connected!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
and here is my client class
package client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class Client{
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12110);
OutputStream os = socket.getOutputStream();
os.write("FirstName,LastName\nWaslley,Souza\nJohn,Snow".getBytes());
os.flush();
socket.shutdownOutput();
BufferedReader soc_in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = soc_in.readLine();
System.out.println("Response: " + response);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
here is the error I get:
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at client.Client.main(Client.java:23)
This happens because your server code exits after accepting a socket connection. Consequently, the JVM of this server will exit and (among others) close all socket connections it holds. This results in a SocketException on the client side.
To fix this, you should prevent the server's JVM from exiting, for instance by nesting the accept() call in a while loop:
public class Server {
public static void main(String[] args) {
try {
ServerSocket socket = new ServerSocket(12110);
while (true) {
Socket s = socket.accept();
System.out.println("Connected! to " + s);
}
} catch (final Exception e) {
e.printStackTrace();
}
}
}
Server Code:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Class1 {
//static ServerSocket variable
private static ServerSocket server;
//socket server port on which it will listen
private static int port = 12110;
public static void main(String args[]) throws IOException, ClassNotFoundException {
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while (true) {
System.out.println("Waiting for the client request");
//creating socket and waiting for client connection
Socket socket = server.accept();
//read from socket to ObjectInputStream object
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//create ObjectOutputStream object
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//write object to Socket
oos.writeObject("Hi Client " + message);
//close resources
ois.close();
oos.close();
socket.close();
//terminate the server if client sends exit request
if (message.equalsIgnoreCase("exit")) {
break;
}
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}
}
Client Code:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException {
//get the localhost IP address, if server is running on some other IP, you need to use that
InetAddress host = InetAddress.getLocalHost();
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
//establish socket connection to server
socket = new Socket(host.getHostName(), 12110);
//write to socket using ObjectOutputStream
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Sending request to Socket Server");
oos.writeObject("SEND SOME DATA");
//read the server response message
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
//close resources
ois.close();
oos.close();
Thread.sleep(100);
}
}
do in this way.
yo #Mike sorry was not clear last time dig in this is the full server code
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
public class Serv1 {
public static void main(String[] args) {
new Serv1().start();
}
public void start(){
String input = "";
try(ServerSocket socket = new ServerSocket(12110)) {
System.out.println("Connected!");
while (true) {
try(Socket server = socket.accept()){
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream(), "UTF-8"));
PrintStream echo = new PrintStream(server.getOutputStream());
while ((input = in.readLine()) != null && !input.equals(".")) {
System.out.println(input);
echo.println("Echoed: " + input);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This should do it
String input= "";
Socket server=socket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream(), "UTF-8"));
PrintStream echo = new PrintStream(server.getOutputStream());
while((input = in.readLine()) != null && !input.equals(".")) {
System.out.println(input);
echo.println("echo: "+input);
}

“java.lang.UnsupportedOperationException: Not supported yet.”

I am making a TCP project in java.
I want to build a TCP connection in java with serial communication from a microcontroller.
I want to do that with Multithreading.
But when I run my server and client , and I send a message from my client to my server. Then I have the following error in the TCPserver :
"Exception in thread "Thread-0" java.lang.UnsupportedOperationException: Not supported yet.
at serialPort.openPort(serialPort.java:30)
at Client.run(TCPserver.java:63)"
Here is my TCPservercode :
import java.io.*;
import java.net.*;
import java.io.IOException;
import jssc.SerialPort;
import jssc.SerialPortException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import jssc.SerialPortList;
import jssc.*;
import jssc.SerialPort;
import jssc.SerialPortException;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
ServerSocket welcomeSocket = new ServerSocket(6789);
SerialPort serialPort = new SerialPort("COM3");
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
if (connectionSocket != null)
{
Client client = new Client(connectionSocket);
client.start();
}
}
}
}
class Client extends Thread
{
private Socket connectionSocket;
private String clientSentence;
private String capitalizedSentence;
private BufferedReader inFromClient;
private DataOutputStream outToClient;
public Client(Socket c) throws IOException
{
connectionSocket = c;
}
public void run()
{
try
{
inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
serialPort.openPort();//Open serial port
serialPort.setParams(SerialPort.BAUDRATE_115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
System.out.println("Received: " + clientSentence);
serialPort.writeString( clientSentence + "\r\n");
//Thread.sleep(1000);
String buffer = serialPort.readString();//Read 10 bytes from seri
// Thread.sleep(1000);
outToClient.writeBytes(buffer);
System.out.println(buffer);
serialPort.closePort();
connectionSocket.close();
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and my TCPclient code :
import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
while(true){
String sentence;
String modifiedSentence;
Socket clientSocket = new Socket("localhost", 6789);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
}
My original serial communication code :
package sensornode_Jens;
import java.io.IOException;
import jssc.SerialPort;
import jssc.SerialPortException;
import java.util.Scanner;
import jssc.SerialPortList;
import jssc.*;
import jssc.SerialPort; import jssc.SerialPortException;
public class Main {
public static void main(String[] args) {
// getting serial ports list into the array
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
System.out.println("There are no serial-ports :( You can use an emulator, such ad VSPE, to create a virtual serial port.");
System.out.println("Press Enter to exit...");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
for (int i = 0; i < portNames.length; i++){
System.out.println(portNames[i]);
////
SerialPort serialPort = new SerialPort("/dev/ttyACM0");
try {
serialPort.openPort();//Open serial port
serialPort.setParams(SerialPort.BAUDRATE_115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
Scanner input = new Scanner(System.in);
String scommand = input.nextLine();
serialPort.writeString( scommand + "\r\n");
String buffer = serialPort.readString();//Read 10 bytes from serial port
System.out.println(buffer);
serialPort.closePort();
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
}
Can anybody help me?
Looking through the Google Code page for jssc on: https://code.google.com/archive/p/java-simple-serial-connector/
When reviewing the examples they use:
SerialPort serialPort = new SerialPort("COM1");
Which I see set in the TCPServer class but not in the Client class where
serialPort.openPort();
is called.
So you may need to initialize serialPort inside your Client class instead of your TCPServer class, before calling openPort on it.
I found no reference to the openPort method throwing a UnsupportedOperationException.

Unable to receive data on server side (Java Socket Programming)

A single client connects to a single server.
I'm unable to display the text sent from the client.
Am I not sending the text properly from client or not receiving the text properly on Server?
Is there another way to check from the code? (on client side that the data has been sent) or (on server side that the data has been received)
package com.company;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
public class ChatServer {
public static void main(String[] args) throws IOException {
ChatServer chatServer = new ChatServer();
chatServer.go();
}
private void go() throws IOException {
//Generate a random number and write to a text file
Random randomGenerator = new Random();
int randomInt = 1024 + randomGenerator.nextInt(64511);
PrintWriter printWriter = new PrintWriter("port.txt");
printWriter.write(String.valueOf(randomInt));
printWriter.flush();
//Create Server on a port using that random number
ServerSocket serverSocket = new ServerSocket(randomInt);
System.out.println("Server on Port: "+randomInt);
//Start Accepting Clients
ClientHandler clientHandler= new ClientHandler(serverSocket);
Thread t = new Thread(clientHandler);
t.start();
}
private class ClientHandler implements Runnable {
ServerSocket serverSocket;
BufferedReader bufferedReader;
PrintWriter writer;
Socket socket;
public ClientHandler(ServerSocket sSocket) throws IOException {
serverSocket = sSocket;
}
public void run() {
while (true)
{
String message;
try {
//Accept A connection and assign a socket for this client
socket = serverSocket.accept();
System.out.println("Connection Established");
//Read Message
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
while( (message = bufferedReader.readLine()) != null)
{
//Display it on the console
System.out.println("From Client: " + message);
//Send it back to the client
writer = new PrintWriter(socket.getOutputStream());
writer.println("Your message is: " + message);
writer.flush();
//Send your message
writer.write("This is default message");
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
This is Client Side Code
package com.company;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient {
Socket socket;
public static void main(String[] args) throws IOException {
ChatClient chatClient = new ChatClient();
chatClient.go();
}
private void go() throws IOException {
//Read Port number from file
FileReader fileReader = new FileReader("port.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
int port = Integer.parseInt(bufferedReader.readLine());
//Connect to socket on the port number
System.out.println("Connecting to Server on: "+port);
socket = new Socket("127.0.0.1",port);
//Initiate sender thread
ChatSender chatSender = new ChatSender(socket);
Thread sender = new Thread(chatSender);
//Initiate receiver thread
ChatReceiver chatReceiver = new ChatReceiver(socket);
Thread receiver = new Thread(chatReceiver);
sender.start();
receiver.start();
}
public class ChatSender implements Runnable
{
BufferedWriter bufferedWriter;
public ChatSender(Socket socket) throws IOException {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
bufferedWriter = new BufferedWriter(outputStreamWriter);
}
public void run()
{
while (true)
{
//get text from console
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println("To Server: "+input);
try {
System.out.println("Sending data");
//write to server
bufferedWriter.write(input);
//flush the text
bufferedWriter.flush();
System.out.println("sent data");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ChatReceiver implements Runnable
{
BufferedReader bufferedReader;
public ChatReceiver(Socket socket) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
}
public void run()
{
try {
while (true)
{
Thread.sleep(1000);
System.out.println("Receiving data");
String output = bufferedReader.readLine();
System.out.print("From Server: "+output);
System.out.println("Received data");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Usual problem. You're reading lines, but you aren't sending lines. Change write() to println().

java tcp socket can't send file to server side

I'm new to java socket programming, this program allows TCP server to have a multi-thread that can run concurrently. I try to send the txt file from one client(has another client that will sent file at the same time) to the server side and ask server to send "ok" status message back to client side. But it seems that the server can't receive any file from the client and the strange thing is if i delete the receiveFile() method in my client class, the server is able to recieve the file from client. Can somebody help me?
Server.class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
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;
ServerConnection (Socket clientSocket) throws SocketException
{
this.clientSocket = clientSocket;
setPriority(NORM_PRIORITY - 1);
}
public void run()
{
try{
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream outToClient = clientSocket.getOutputStream();
PrintWriter printOutPut = new PrintWriter(outToClient,true);
while(inFromClient.ready())
{
String request = inFromClient.readLine();
System.out.println(request);
System.out.println("test");
}
printOutPut.write("HTTP/1.1 200 OK\nConnection: close\n\n");
printOutPut.write("<b> Hello sends from Server");
printOutPut.flush();
printOutPut.close();
clientSocket.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
Client.class
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SmallFileClient {
static String file="test.txt";
static PrintWriter outToServer;
static Socket socket;
public static void main(String[] args) throws IOException
{
final int PORT=20020;
String serverHostname = new String("127.0.0.1");
socket = new Socket(serverHostname, PORT);
outToServer = new PrintWriter(socket.getOutputStream(),true);
sendFile();
receiveFile();
outToServer.flush();
outToServer.close();
socket.close();
}
//read file and send file to server
public static void sendFile() throws IOException
{
BufferedReader br=new BufferedReader(new FileReader(file));
try
{
String line = br.readLine();
while(line!=null)
{
//send line to server
outToServer.write(line);
line=br.readLine();
}
}catch (Exception e){System.out.println("!!!!");}
br.close();
}
//get reply from server and print it out
public static void receiveFile() throws IOException
{
BufferedReader brComingFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
try
{
String inline = brComingFromServer.readLine();
while(inline!=null)
{
System.out.println(inline);
inline = brComingFromServer.readLine();
}
}catch (Exception e){}
}
}
Get rid of the ready() test. Change it to:
while ((line = in.readLine()) != null)
{
// ...
}
readLine() will block until data is available. At present you are stopping the read loop as soon as there isn't data available to be read without blocking. In other words you are assuming that `!ready()! means end of stream. It doesn't: see the Javadoc.

Categories