java.net.SocketException: Connection reset error - java

I am using socket in Java.
Client send a name and phone number.
then sever get client data and encrypt it.
however problem accrue.
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at java.io.DataInputStream.readFully(DataInputStream.java:178)
at java.io.DataInputStream.readUTF(DataInputStream.java:592)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
at chat.QrcodeServer.dataEnc(QrcodeServer.java:45)
at chat.QrcodeServer.main(QrcodeServer.java:25)
Server:
import java.io.*;
import java.net.*;
public class QrcodeServer{
public static void main (String[] args){
ServerSocket ss = null;
Socket client = null;
int port = 10000;
try {
ss = new ServerSocket(port);
System.out.println("Service is started in "+ port);
}catch (IOException ee){
ee.printStackTrace();
}
try{
while (true){
client = ss.accept();
System.out.println("Client Info:" + client);
dataEnc(client);
}
}catch(IOException ee){
ee.printStackTrace();
}
}
public static void dataEnc(Socket client){
// Get an input file handle from the socket and read the input
InputStream cin=null;
String data=null;
String password=null;
try {
//get client Data Stream
cin = client.getInputStream();
DataInputStream dis = new DataInputStream(cin);
//get data
data = new String (dis.readUTF());
password = new String(dis.readUTF());
System.out.println(data);
System.out.println(password);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//To make password hash
String passwordTemp = Crypto.getPassword(password);
try {
//encrypt data through passwordTemp
byte[] cipher = Crypto.encrypt(data,passwordTemp);
//printout the cipher data
System.out.print("cipher: ");
for(int i=0; i<cipher.length;i++){
System.out.print(Integer.toHexString(0xff&cipher[i])+" ");
}
System.out.println();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket server = null;
String ip = "ip addr";
int port = 10000;
try{
server = new Socket(ip, port);
System.out.println("server: "+ip + "and port is "+ port );
sendInfo(server);
}catch(IOException e){
e.printStackTrace();
}
}
public static void sendInfo (Socket soc){
// Get a communication stream associated with the socket
OutputStream cout;
try {
cout = soc.getOutputStream();
DataOutputStream dos = new DataOutputStream (cout);
String name="kevin";
String phone="123456780";
String password="password";
String data = name+phone;
// Send a data
dos.writeUTF(data);
dos.writeUTF(password);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It works in localhost and local interior network.
but problem above accrue when client connected from internet.
What might be the problem?

Related

Java Socket: cannot communicate between two computers using Socket

I have made two programs using Java that can communicate using Socket and They work fine on my own PC. But when I try to do the same thing between two computers, It does not work, as if the computers cannot find each other or something else. (I get the IP Address of the computer that works as the server using ipconfig in CMD)
What ever is wrong here, is not about the code. I even turned off the firewalls on both computers, but I nothing changed. Can anyone help me out?
MyServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class MyServer {
// Scanner Object
static Scanner scan = new Scanner(System.in);
// Objects
static ServerSocket serverSocket;
static Socket socket;
static DataInputStream dIs;
static DataOutputStream dOut;
public static void main(String[] args) {
try {
// Setting Up Message
System.out.println("Server Waiting For Connections...");
// Setup Server Socket
serverSocket = new ServerSocket(6666);
// Accept Client Connection Request
socket = serverSocket.accept();
// Confirmation Message
System.out.println("Client Connected.");
// Data Input Stream
dIs = new DataInputStream(socket.getInputStream());
// Data Output Stream
dOut = new DataOutputStream(socket.getOutputStream());
String Input = "";
while (!Input.equalsIgnoreCase("close Connection")) {
// Read Client Message
Input = dIs.readUTF();
System.out.print("\nClient: " + Input);
if (!Input.equalsIgnoreCase("close Connection")) {
// Send Server-Side Response
System.out.print("\nResponse: ");
dOut.writeUTF(scan.nextLine());
dOut.flush();
} else {
dOut.writeUTF("Connection Closed.");
dOut.flush();
}
}
closeConnections();
} catch (Exception ex) {
// Error Message
System.out.println("Error: " + ex);
closeConnections();
}
}
public static void closeConnections() {
try {
// Close Connection
dIs.close();
socket.close();
serverSocket.close();
System.out.println("Connection Closed.");
} catch (Exception ex) {
System.out.println("Could Not Close Connections.");
}
}
}
MyClient.java
import java.io.*;
import java.net.*;
import java.util.*;
public class MyClient {
// Scanner Object
static Scanner scan = new Scanner(System.in);
// Objects
static Socket socket;
static DataInputStream dIs;
static DataOutputStream dOut;
public static void main(String[] args) {
try {
// Setup Connection Socket For Client
socket = new Socket("localhost",6666);
// Data Input Stream
dIs = new DataInputStream(socket.getInputStream());
// Data Output Stream
dOut = new DataOutputStream(socket.getOutputStream());
String Input = "";
while (!Input.equalsIgnoreCase("Close Connection")) {
// Send Client-Side Message
System.out.print("\n- Client Message: ");
dOut.writeUTF(scan.nextLine());
dOut.flush();
// Read Server Message
Input = dIs.readUTF();
System.out.print("\nServer Response: " + Input);
}
closeConnections();
} catch (Exception ex) {
// Error Message
System.out.println(ex);
closeConnections();
}
}
public static void closeConnections() {
try {
// Close Connection
dIs.close();
dOut.close();
socket.close();
} catch (Exception ex) {
System.out.println("Could Not Close Connections.");
}
}
}

How can a server broadcast a message to other clients?

The program is intended to have multiple clients connect to a single server and the clients are able to send and receive messages among other clients.
For example if Client A says "Hi", Client B and Client C connected to the server would also receive "Hi".
In my current code, the server only receives the messages sent by the clients.
I'm currently looking for a solution to have the server broadcast the message sent by a client (eg. ClientA) to other clients. Any advice would be much appreciated.
This server class handles the connections of multiple clients with the use of threads:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
class EchoThread extends Thread {
private Socket socket;
//constructor
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
}
#Override
public void run() {
DataInputStream inp = null;
try {
inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
//print whatever client is saying as long as it is not "Over"
String line = "";
while (!line.equals("Over")) {
try {
line = inp.readUTF();
System.out.println(line);
} catch (IOException e) { System.out.println(e); }
}
//closes connection when client terminates the connection
System.out.print("Closing Connection");
socket.close();
} catch (IOException e) { System.out.println(e); }
}
}
public class Server {
private static final int PORT = 5000;
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;
//starts the server
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server started");
System.out.println("Waiting for a client ...\n");
} catch (IOException e) { System.out.println(e); }
//while loop to accept multiple clients
int count = 1;
while(true) {
try {
socket = serverSocket.accept();
System.out.println("Client " + count + " accepted!");
count++;
} catch (IOException e) { System.out.println(e); }
//starts the server thread
new EchoThread(socket).start();
}
}
}
and this is the client class (I have multiple instances of this code running):
import java.net.*;
import java.io.*;
public class ClientA {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream output = null;
public ClientA(String address, int port) {
//establish connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
//takes input from terminal
input = new DataInputStream(System.in);
//sends output to the socket
output = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) { System.out.println(e); }
//string to read message from input
String line = "";
//keep reading until "Over" is input
while (!line.equals("Over")) {
try {
line = input.readLine();
output.writeUTF(line);
} catch (IOException e) { System.out.println(e); }
}
//close the connection
try {
input.close();
output.close();
socket.close();
} catch (IOException e) { System.out.println(e); }
}
public static void main (String args[]) {
ClientA client = new ClientA("127.0.0.1", 5000);
}
}
Do feel free to correct me on my code comments as I'm still not very familiar with socket programming.
You did well. Just add a thread to receive message in ClientA; and store socket clients in Server.
In fact, Server is also a "client" when is send message to client.
I add some code based on your code. It works well, hope it's helpful.
class EchoThread extends Thread {
//*****What I add begin.
private static List<Socket> socketList = new ArrayList<>();
//*****What I add end.
private Socket socket;
//constructor
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
socketList.add(socket);
}
#Override
public void run() {
DataInputStream inp = null;
try {
inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
//print whatever client is saying as long as it is not "Over"
String line = "";
while (!line.equals("Over")) {
try {
line = inp.readUTF();
System.out.println(line);
//*****What I add begin.
sendMessageToClients(line);
//*****What I add end.
} catch (IOException e) { System.out.println(e); break;}
}
//closes connection when client terminates the connection
System.out.print("Closing Connection");
socket.close();
} catch (IOException e) { System.out.println(e); }
}
//*****What I add begin.
private void sendMessageToClients(String line) throws IOException {
for (Socket other : socketList) {
if (other == socket) {
continue;//ignore the sender client.
}
DataOutputStream output = new DataOutputStream(other.getOutputStream());
output.writeUTF(line);
}
}
//*****What I add end.
}
public class ClientA {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream output = null;
public ClientA(String address, int port) {
//establish connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
//takes input from terminal
input = new DataInputStream(System.in);
//sends output to the socket
output = new DataOutputStream(socket.getOutputStream());
//*****What I add begin.
//Here create a thread to receive message from server.
DataInputStream inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
new Thread(() -> {
while (true) {
String str;
try {
str = inp.readUTF();
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();//error.
break;
}
}
}, "Client Reveiver.").start();
//*****What I add end.
} catch (IOException e) { System.out.println(e); }
//string to read message from input
String line = "";
//keep reading until "Over" is input
while (!line.equals("Over")) {
try {
line = input.readLine();
output.writeUTF(line);
} catch (IOException e) { System.out.println(e); }
}
//close the connection
try {
input.close();
output.close();
socket.close();
} catch (IOException e) { System.out.println(e); }
}
I would have a single server thread which would maintain a register of the clients, possibly in a concurrent collection. Then I would send each message received from a client to all other clients.

Socket don't save values in list

I'm new in network developing in Java and I want to create a simple Socket server, that get values from client and collects all of them in ArrayList. I wrote an example code, but in server side it not collecting the strings. This is my server side:
Server
public class ServerSideSocket extends Thread{
private ServerSocket serverSocket;
private Socket socket;
private ArrayList<String> list = new ArrayList<String>();
DataInputStream inData;
DataOutputStream outData;
public ServerSideSocket(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
public void run() {
while(true) {
try{
System.out.println("Waiting for connection...");
socket = serverSocket.accept();
System.out.println("Connected!" );
inData = new DataInputStream(socket.getInputStream());
outData = new DataOutputStream(socket.getOutputStream());
System.out.println(inData.readUTF());
list.add(inData.readUTF());
System.out.println("------------ VALUES ---------");
for (String value: list) {
System.out.println(value);
}
System.out.println("------------ END VALUES ---------");
outData.writeUTF("Message saved!");
outData.flush();
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inData.close();
outData.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
int port = 9999;
try {
Thread t = new ServerSideSocket(port);
t.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
and Client:
public class ClientSideSocket {
public static void main(String[] args) {
String serverName = "localhost";
int port = 9999;
String line = "";
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream out = client.getOutputStream();
DataOutputStream outData = new DataOutputStream(out);
InputStream in = client.getInputStream();
DataInputStream inData = new DataInputStream(in);
outData.writeUTF("Simple text");
outData.flush();
System.out.println("Response from server: " + inData.readUTF());
System.out.println("You can write more messages!");
System.out.println();
client.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
what is wrong in my code?
This happens because you try to read twice from the data stream by calling inData.readUTF() method. First call successfully reads data from the stream, but instead of saving result you try to perform another read 2 lines below.
readUTF() is blocking method and thus it waits for another portion of data which never comes from the same client. That's why your server hungs forever
What you want to do is to read once and store result into local variable:
String res = inData.readUTF();
list.add(res);
You are writing data once as "Simple Text" which you can read only once.
Where in your code you are first reading it
System.out.println(inData.readUTF());
list.add(inData.readUTF());
Instead of this you should first store it in a String and then use it.
String message = inData.readUTF();
System.out.println(message);
list.add(message);

Server not reading data

I had modified the Java Socket Tutorials code to allow the client to send a string array and the server passes the array back with the strings in the array changed. It works fine.
Now I am trying to create a server class that behaves as a server component. The component basically only receives data from the client and prints the client data. However, the server accepts the connection but does not reading. Hence, to see what was happening, I tried to just run a server socket from main. Even that is not working. I am not sure why the tutorial code works but not when I do the exact thing in my code. I do not understand the reason for such peculiar behavior.
Following is the Java Tutorial Code for Server
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
int portNumber = Integer.parseInt(args[0]);
try
(
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
ObjectInputStream objIn = new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream objOut = new ObjectOutputStream(clientSocket.getOutputStream());
) {
String str[][] = (String [][])objIn.readObject();
if(str != null)
{ for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
System.out.println(str[i][j]);
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
str[i][j] ="Success";
objOut.writeObject(str);
}
} catch (IOException | ClassNotFoundException ecp) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(ecp.getMessage());
}
}
}
The following is the client from Java Tutorial
public class EchoClient {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java EchoClient <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket echoSocket = new Socket(hostName,portNumber);
ObjectOutputStream objOut = new ObjectOutputStream(echoSocket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(echoSocket.getInputStream());
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
) {
String str[][] = new String[8][8];
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
str[i][j] = "Test";
objOut.writeObject(str);
System.out.println("String array sent");
str = (String[][])objIn.readObject();
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
System.out.println(str[i][j]);
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now the following is my simple server attempt which does not read when EchoClient sends data. It connects but not read.
import java.net.*;
import java.io.*;
public class Server
{
public static void main (String[] args)
{
try {
ServerSocket serv = new ServerSocket(8000);
Socket client = serv.accept();
ObjectInputStream objin = new ObjectInputStream(client.getInputStream());
String[][] str = (String[][]) objin.readObject();
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
str[i][j] ="Success";
System.out.println(str[0][0]);
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please let me know where I am going wrong. Note the Java tutorial classes EchoServer and EchoClient work as expected. But I am unable to replicate it on my own. The Server class accepts EchoClient but does not read.
EDIT:Following is my fixed attempt. This works as intended.
Server class:
import java.net.*;
import java.io.*;
public class Server
{
ServerSocket serverSocket;
Socket clientSocket;
String hostname;
int portNo = 8000;
String clientData;
int count = 0;
public Server()
{
try {
serverSocket = new ServerSocket(portNo);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void startReceiving()
{
try {
if(clientSocket == null)
{ clientSocket = serverSocket.accept();
System.out.println("Client Connected");
}
ObjectInputStream objIn = new ObjectInputStream(clientSocket.getInputStream());
//String strtemp[][];
String data;
while(true)
{
if((data = (String)objIn.readObject()) != null)
{
this.clientData = data;
System.out.println(this.clientData);
break;
}
/*if((strtemp = (String[][]) objIn.readObject())!= null)
{
str = strtemp;
System.out.println("received data");
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
System.out.println(str[i][j]);
}
else
System.out.println("no data received");*/
}
sendData();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
try {
clientSocket.close();
clientSocket = null;
startReceiving();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public void sendData()
{
/*for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
str[i][j] ="Success";*/
this.clientData = "client request response" + count;
count++;
ObjectOutputStream objOut;
try {
objOut = new ObjectOutputStream(clientSocket.getOutputStream());
objOut.writeObject(this.clientData);
objOut.flush();
startReceiving();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main (String[] args)
{
Server server = new Server();
server.startReceiving();
}
}
Following is the client:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TestClient
{
Socket connection;
String hostname = "localhost";
int portNo = 8000;
String incomingData;
int count;
public TestClient()
{
try {
connection = new Socket(hostname,portNo);
count = 0;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void receiveData()
{
ObjectInputStream in;
try {
in = new ObjectInputStream(this.connection.getInputStream());
String serverMessage;
while (true)
{
if((serverMessage = (String)in.readObject()) != null)
{
System.out.println(serverMessage);
break;
}
}
if(count < 5)
sendData();
else
{
in.close();
this.connection.close();
}
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
}
public void sendData()
{
try {
ObjectOutputStream out = new ObjectOutputStream(connection.getOutputStream());
out.writeObject("Client request" + count);
out.flush();
count++;
receiveData();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[])
{
TestClient testClient = new TestClient();
testClient.sendData();
}
}
Your client creates an ObjectInputStream but the server doesn't create a corresponding ObjectOutputStream, so the client blocks waiting for the object stream header that is never sent.
Also you should get rid of all the Readers and Writers. You can't combine different kinds of reader/writer/stream over the same socket.
Also your server doesn't close the socket properly.
Also the error message 'couldn't get I/O for ...' is meaningless. I know it comes from the Java Tutorial, and I complained to them about it decades ago, but you should never make up your own error message and throw away the one that comes with the exception like this.
You did not understand properly how this application is designed.
You removed the part where you send str[i][j] but still set it to success in the loop, this is illogical. At first run, the server will read nothing, therefore it will never set any values to the array and this is why System.out.println(str[0][0]) print nothing.
You have to understand that in the example from the tutorial, the first loop read what is received
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
System.out.println(str[i][j]);
Then the second loop simply write success everywhere and re-send the data to the EchoClient.
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
str[i][j] ="Success";
objOut.writeObject(str);
Using this main
public static void main (String[] args)
{
int portNumber = 8000;
try {
ServerSocket serv = new ServerSocket(portNumber);
Socket client = serv.accept();
ObjectInputStream objin = new ObjectInputStream(client.getInputStream());
ObjectOutputStream objOut = new ObjectOutputStream(client.getOutputStream());
String str[][] = (String[][]) objin.readObject();
if(str != null)
{
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
System.out.println(str[i][j]);
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
str[i][j] ="Success";
objOut.writeObject(str);
}
System.out.println(str[0][0]);
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Which is the one you used, but where I re-added the second loop and writing, will print on both Client and Server.
You should also consider handling the Socket termination in a finally block to make sure it is closed whatever happen to your program.
try
{
...
}
catch(IOEXception e)
{
...
}
finally
{
if(socket != null)
socket.close();
}
Make sure to declare the socket outside of the try scope so it is accessible in the finally.

Client server programming in java with options to user

My task is to display three options to the user 1)connect to server 2)post data 3)disconnect. I am having trouble in sending the file to the server. "The file needs to be sent from client to server". I am new to socket programming and however I try the connection is being reset while I try to send the file to server.
server
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class Server extends Thread {
private ServerSocket serverSocket;
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
public void run() {
boolean flag = true;
while (flag) {
try {
System.out.println("Waiting for client on port "
+ serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
Scanner reader = new Scanner(server.getInputStream());
File file = new File("compile.txt");
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(
file));
while (reader.hasNextLine()) {
String str = reader.next();
fileWriter.write(str);
System.out.println("" + str);
}
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
int port = 4444;
try {
Thread t = new Server(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
client
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class Client {
public static void main(String[] args) {
Socket client = null;
boolean flag = true;
while (flag) {
System.out
.println("Please enter your choice\n1.Connect to Server\n2.Post Data\n3.Disconnect from Server");
Scanner userChoice = new Scanner(System.in);
int choice = userChoice.nextInt();
String serverName = "localhost";
int port = 4444;
if (choice == 1) {
try {
System.out.println("Connecting to " + serverName
+ " on port " + port);
client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
} catch (IOException e) {
e.printStackTrace();
}
} else if (choice == 2) {
System.out.println("enter path of file to be compiled");
Scanner pathReader = new Scanner(System.in);
String path = pathReader.next();
pathReader.close();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path));
while ((line = br.readLine()) != null) {
PrintWriter writer = new PrintWriter(
client.getOutputStream(), true);
writer.write(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
client.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (choice == 3) {
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
System.out.println("enter a valid input");
}
}
}
First of all client-server socket connections and applications are pretty complicated. I'd recommend reading:
http://www.oracle.com/technetwork/java/socket-140484.html#sockets
couple of things to consider:
make sure there is nothing running on the socket.
make sure that the server is listening
You are running the server on one thread, so if it finishes at all then it won't restart
You are not closing the fileWriter once you have finished writing -
please post your output/any stacktraces you have

Categories