Java Web Client Remote Connection - java

I am writing a web server/client. When communicating over localhost, things are fine. But when communicating using my public IP address, an exception is thrown. Here is a minimal working example:
import java.io.*;
import java.text.*;
import java.util.*;
import java.net.*;
public class Server
{
public static void main(String[] args) throws IOException
{
int port = 80;
// server is listening on port
ServerSocket ss = new ServerSocket(port);
// running infinite loop for getting
// client request
while (true)
{
Socket s = null;
try
{
// socket object to receive incoming client requests
s = ss.accept();
System.out.println("A new client is connected : " + s);
// obtaining input and out streams
ObjectOutputStream odos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream odis = new ObjectInputStream(s.getInputStream());
Info info = new Info();
info.color = 1;
odos.writeObject(info);
while(true){
info = (Info)odis.readObject();
if(info.exit){
break;
}
}
// closing resources
odis.close();
odos.close();
}
catch (Exception e){
s.close();
e.printStackTrace();
}
}
}
}
And the Client:
import java.util.*;
import java.net.*;
import java.io.*;
import java.net.InetAddress;
public class Client
{
public static void main(String[] args) {
if(args.length>0){
ip_name = args[0];
}
if(args.length>1){
port = Integer.parseInt(args[1]);
}
network();
}
private static String ip_name = "localhost";
private static int port = 80;
private static void network(){
try
{
System.out.println("Connecting to network");
InetAddress ip = InetAddress.getByName(ip_name);
// establish the connection with server port
Socket s = new Socket(ip, port);
System.out.println("Connected");
// obtaining input and out streams
ObjectOutputStream odos = new ObjectOutputStream(s.getOutputStream());
InputStream i = s.getInputStream();
ObjectInputStream odis = new ObjectInputStream(i);
// get what color we are
int color = ((Info)odis.readObject()).color;
System.out.println(color);
//say we are done
Info info = new Info();
info.exit = true;
odos.writeObject(info);
System.out.println("Shutting down");
}catch(Exception e){
e.printStackTrace();
}
}
}
When using localhost, the client prints out, as expected:
Connecting to network
Connected
1
Shutting down
but when I replace localhost with my public IP:
Connecting to network
Connected
java.io.StreamCorruptedException: invalid stream header: 48545450
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Client.network(Client.java:36)
at Client.main(Client.java:14)
48545450 is hex for "HTTP", but beyond that I can't tell what the problem is. Any ideas?

When I tried running your code I got error "Info is non-serilizable". I have modified your Info class as follows.
import java.io.Serializable;
public class Info implements Serializable {
public int color;
public boolean exit;
}
You need to implement Serializable If you are sending class data. Using this you can persist object info over a network.

Related

In java socket programming chat application, Is it possible to create a individual chat for each clients like whatsapp?

Now I'm done with the application which have the server and client, server accepts the client request and add the client object into the Arraylist and starts a new thread for each clients. when multiple clients connects, clients can list all the clients, and they can send a message to any clients in the list. For example client1, client2, client3 connects to the server client1 and client2 sending a message to the client3,It will be printed in client3 console. all working fine. Now i need to add additional feature that each clients sends a message in individual chat, if client1 opens a chat with client2 the conversation between those two clients only should be displayed, not client3 messages, and vice versa. To do that implementation do i need any additional concept like multi threading. I'm not asking a source code, I'm just asking a idea to implement the above feature.
Can anyone tell me the suggestion or reference to implement separate chats for different clients... Need to keep the old messages until the server goes offline?
Server.java
package server;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.*;
import java.util.Vector;
public class Server {
static Vector<ClientHandler> AllClients = new Vector<ClientHandler>();
public static void main(String args[]) throws Exception {
try {
ServerSocket ss = new ServerSocket(1111);
System.out.println("Server Started");
while(true) {
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String clientname = dis.readUTF();
System.out.println("Connected With : "+clientname);
ClientHandler client = new ClientHandler(s,clientname);
Thread t = new Thread(client);
AllClients.add(client);
t.start();
System.out.println("Ready to accept connections...");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ClientHandler.java
package server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class ClientHandler extends Thread{
private DataInputStream in;
private DataOutputStream out;
private String ClientName;
private boolean login;
private Socket Socket;
Scanner sc = new Scanner(System.in);
ClientHandler(Socket s,String name) throws Exception{
this.in = new DataInputStream(s.getInputStream());
this.out = new DataOutputStream(s.getOutputStream());
this.login = true;
this.ClientName = name;
this.Socket = s;
}
public void run() {
while(true) {
try {
String received = in.readUTF();
if(received.equalsIgnoreCase("logout")) {
this.login = false;
this.out.writeUTF("logout");
int i;
for(i = 0; i < Server.AllClients.size(); i++) {
if(this.ClientName.equals(Server.AllClients.get(i).ClientName))
break;
}
Server.AllClients.remove(i);
System.out.println(this.ClientName+" logged out");
this.Socket.close();
break;
}
if(received.equalsIgnoreCase("getlist")) {
for(int i = 0; i < Server.AllClients.size(); i++) {
out.writeUTF(i+1 +", "+Server.AllClients.get(i).ClientName);
}
continue;
}
if(received.contains(",")) {
String[] Message = received.split(",");
for(ClientHandler c : Server.AllClients) {
if(c.ClientName.equalsIgnoreCase(Message[1]) && c.login) {
c.out.writeUTF(this.ClientName +" : "+ Message[0]);
c.out.flush();
break;
}
}
}
}catch(Exception e) {
System.out.println("Error :"+e.getMessage());
}
}
try {
this.in.close();
this.out.close();
}catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
Client.java
package client;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
static DataInputStream dis;
static DataOutputStream dos;
static Socket s;
public static void main(String args[])throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Cient Name : ");
String name = sc.nextLine();
s = new Socket("localhost",1111);
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(name);
Thread sendMessage = new Thread(new Runnable()
{
#Override
public void run() {
while (true) {
String msg = sc.nextLine();
try {
dos.writeUTF(msg);
if(msg.equalsIgnoreCase("logout")) {
System.out.println("Logged out");
break;
}
} catch (IOException e) {
System.out.println("Error in send method :"+e.toString());
}
}
}
});
Thread readMessage = new Thread(new Runnable()
{
#Override
public void run() {
while (true) {
try {
String msg = dis.readUTF();
if(msg.equalsIgnoreCase("logout")) {
System.out.println("Logged out");
break;
}
System.out.println(msg);
} catch (IOException e) {
System.out.println("Error in read method :"+e.getMessage());
}
}
}
});
sendMessage.start();
readMessage.start();
}
}
If my code have any irrelevant statements please do suggest a better way to optimise the code
The first answer is: yes it is possible.
The second answer: it's not about threading, you have to think in the first place (it's important, but not in the frist place).
the third answer: as i understand your code, the main data-structre is the collection of clients and their handler. In my opinion there is a further abstraction-layer missing in between.
In the frist place think about a data structure like "chatRoom". A client connecting to server has to send a "chatRoom"-name to the the server. Than the server creates the chatRoom or adds the client to the chatRooom's client-set. From that point a client can send his messages to the chatRoom not to the client directly anymore.
In a further step: To enable sending messages to inidividual clients you can e.g. enforce a chatRoom for every pair of clients (take care: this can be very expansive), so individual communication between clients is still possible.

Java Multi Client server socket

I am trying to establish a communication between a server (NewServer class) and a client (NewClient class), accepting two Client communications. I know how to do it with one client but not multiple client connections.
Do I have to create 2 readers in the Client class?
Can I do this in a recursive way?
Server Class:
import java.net.*;
import java.io.*;
public class NewServer
{
//Create Server Socket and a Client Socket for each Client.
static ServerSocket server;
static Socket client1;
static Socket client2;
//Create OutputStreams to send information to each Client.
static DataOutputStream client1writer;
static DataOutputStream client2writer;
static final int PORT = 9999;
//Main Method
public static void main(String[]args)
{
//Try-Catch Block for Socket Errors.
try
{
//Create the Server Socket as a Host.
server = new ServerSocket(PORT);
//Connect Client 1 – First run of the Client class.
client1 = server.accept();
client1writer = new
DataOutputStream(client1.getOutputStream());
//Connect Client 2 – Second run of the Client class.
client2 = server.accept();
client2writer = new
DataOutputStream(client2.getOutputStream());
//Assign each Client an ID number – this is how the Client will know
// which individual Client it’s representing in RunTime.
int ID1 = 8675309;
int ID2 = 8675308;
//Tell both Clients which one they are representing.
client1writer.writeInt(ID1);
client2writer.writeInt(ID2);
//Close all Sockets when finished.
client1.close();
client2.close();
server.close();
}
catch (IOException IOex)
{
System.out.println("Server Error.");
}
}
}
Client class:
import java.net.*;
import java.io.*;
public class NewClient {
static Socket client = null;
static final int PORT = 9999;
static final String IP = "localhost";
public static void main(String[] args) throws IOException {
int id1;
int id2;
try{
client = new Socket(IP,PORT);
System.out.println("Connection successful!");
reader = new DataInputStream(client.getInputStream());
id1 = reader.readInt();
id2 = reader.readInt();
System.out.println("The id of the user is " + id);
//Closing everything
client.close();
reader.close();
}catch(IOException error) {
System.err.println("Server error.");
}
}
}
You can achieve it by starting a separate thread (also known as Plain threads for every new client connection and then call server.accept() which runs in a loop. It is useful as an learning example but will not help you achieve what you need as you loose control of threads.
Second way is to use Executor Service which provides better management control over the above solution.

How do I reconnect a client when server is down in Java?

I have a server that accepts sockets from whenever a client connects. I want to be able to shutdown my local server and let my client try to reconnect for about 5 times, and if I start my server the client should indicate that you have reconnected again.
I understand somewhat that this is done in the try{} catch(IOException){Here goes the code for handleing reconnect} I want to use the same socket that I first used to connect. I don't want to create a new Client cause then I have to enter username and stuff like that all over again
I tried to creating a new socket like clientSocket = new Socket("localhost", portnr) but I don't know if this is the correct way to go. If you have examples that answers this please link them. I dont mind reading as long as it is good documented. Thanks in advance!
EDIT.
Here is my Client Class
public class Client {
public static void main(String[] args) {
Client client = new Client();
client.connect();
}
//------------------------------------------------------------
//METHOD CONNECT
//------------------------------------------------------------
private void connect(){
int reConnectTries = 0;
Socket clientsocket;
try {
//------------------------------------------------
//Sets up variables needded for execution
clientsocket = new Socket("localhost", 8900);
DataOutputStream OUT = new DataOutputStream(clientsocket.getOutputStream());
ListenforMessages listen = new ListenforMessages(clientsocket);
//We don't want to enter username all the time
//So this goes not in the while-loop
//------------------------------------------------
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter username");
String username = keyboard.nextLine();
//Sends username to sever so it can be added to a list
OUT.writeUTF(username);
//------------------------------------------------
//------------------------------
//Creates a thread to listen on messages from server(Other clients in this case)
Thread trd = new Thread(listen);
trd.start();
//------------------------------
while (true) {
try {
String sendMessage = keyboard.nextLine();
OUT.writeUTF(sendMessage);
OUT.flush();
} catch (Exception e) {
System.err.println("Could not send message to server. " + e);
}
}
} catch (IOException e) {
System.err.println("Couldnt establish a connection: " + e);
}
}
//------------------------------------------------------------
//CLASS FOR HANDLEING INPUT. We create a class for input on a new thread
//This is cause we don't want it to block other processes.
//----------------------------------------------------------------
class ListenforMessages implements Runnable{
Socket mySocket;
DataInputStream IN;
public ListenforMessages(Socket X) throws IOException {
this.mySocket = X;
}
#Override
public void run() {
try {
IN = new DataInputStream(mySocket.getInputStream());
while (true) {
System.out.println(IN.readUTF());
}
} catch (Exception e) {
System.err.println("Couldn't fetch message from server.Error: " + e);
}
}
}
}
There's a couple of solutions to this problem, but a simple one would to be have the client try to reconnect (open a new connection to the server) at set intervals. For example, you could try something like this to have your client try to reconnect once every 3 minutes:
while(true) {
try {
clientSocket = new Socket("localhost", portnr);
break; // We connected! Exit the loop.
} catch(IOException e) {
// Reconnect failed, wait.
try {
TimeUnit.MINUTES.sleep(3);
} catch(InterruptedException ie) {
// Interrupted.
}
}
}
This way, the client will try to connect, and if it fails, wait for 3 minutes before trying again.
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.NoRouteToHostException;
import java.net.SocketAddress;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.net.ConnectException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
final class TCPClient{
private static Scanner in ;
private static DataOutputStream douts;
private static OutputStream outs;
private static InputStream ins;
private static DataInputStream dins;
private static String ip;
private static Integer port;
private int count = 0;
private static int times;
public TCPClient(){
serverConTest(port);
}
private boolean portIsOpenOrNot(String ip, int port){
try{
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip,port),500);
socket.close();
return true;
}catch(Exception e){
}
return false;
}
private void serverConTest(int port){
while(true){
try{
InetAddress addr = InetAddress.getByName(ip);
SocketAddress sockaddr = new InetSocketAddress(addr,port);
Socket socket = new Socket();
System.out.println("Connecting To server...");
socket.connect(sockaddr);
Thread.sleep(1000);
boolean isactive = true;
if(portIsOpenOrNot(ip,port)){
outs = socket.getOutputStream();
douts = new DataOutputStream(outs);
System.out.println("Sending Request to server:");
while(isactive){
Thread.sleep(1000);
douts.writeUTF("Are you Alive..!");
ins = socket.getInputStream();
dins = new DataInputStream(ins);
System.out.println("Response from server : "+dins.readUTF());
}
}
}catch(SocketException e){
System.out.println("Connection lost");
}catch(IOException e){
break;
}catch(InterruptedException e){
System.out.print("connection timeout in 50 second.");
break;
}
}
}
public static void main(String[] args){
in = new Scanner(System.in);
System.out.print("Enter ip : ");
ip = in.nextLine();
System.out.print("Enter Port : ");
port = Integer.parseInt(in.next());
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future future = executorService.submit(new Runnable() {
public void run() {
new TCPClient();
}
});
try{
future.get(50, TimeUnit.SECONDS);
}catch(InterruptedException e){
}catch(ExecutionException e){
}catch(TimeoutException e){
executorService.shutdownNow();
}
}
}
This sample will give you the complete understanding that when the server restarts then client will reconnects.
I didnt read all your code but this one is working for me
And dont forget to add the Server class and the method send that sends messages...
Client :
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Client {
static Socket sock=null;
static DataInputStream in=null;
static DataOutputStream out=null;
static boolean connected=false;
static String currentip="";
static int currentport=0;
static void refreching(){
try {
in=new DataInputStream(sock.getInputStream());
out=new DataOutputStream(sock.getOutputStream());
Thread gg=new Thread() {
String msg="";
public void run() {
while(connected) {
try {
msg=in.readUTF();
System.out.println(msg);
} catch (IOException e) {
connected=false;
System.out.println("Reconnecing...");
while(!connected)
connect(currentip,currentport);
}
}
}
};
gg.start();
}
catch(Exception e) {
System.out.println("Problem while reading incoming and outgoing"+
"messages!");
connected=false;
}
}
static void connect(String iphost, int port){
try{
sock=new Socket(iphost,port);
currentip=iphost;
currentport=port;
connected=true;
refreching();
System.out.println("Connected!");
}
catch(Exception e){
System.out.println("Cant connect !");
connected=false;
}
}
public static void main(String[] args) {
connect("127.0.0.1",1234); //Example you can enter another's computer ip
//adress if connected to the same network !!!
//Send(Message_To_Server); Dont forget to add the sending code!!!
//Maybe i'll upload a video one day==>how to create a chat application
}

How to make server send a message to client on button click

I have a client and a server. When client connects to server the server sends a message to the client.
If the user clicks on button "New message" I want the server to send a new message to the client.
How can I achieve that?
My code (I have removed all try-Catch)
Client:
private void getExpression() {
Socket s = null;
s = new Socket(serverAddress, serverPort);
out = new ObjectOutputStream(s.getOutputStream());
in = new ObjectInputStream(s.getInputStream());
while (true) {
Expression exp = (Expression) in.readObject();
String message = exp.toString();
expressionLabel.setText(message);
}
}
public void newMessage() throws IOException {
//MAKE SERVER SEND NEW MESSAGE
}
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource().equals(newButton)) {
newMessage();
}
}
Handler:
public class Handler extends Thread {
private Socket socket;
private String address;
public Handler (Socket s) {
socket = s;
address = socket.getInetAddress().getHostAddress();
}
#Override
public void run() {
ObjectInputStream in = null;
ObjectOutputStream out = null;
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
out.writeObject(new Expression());
out.flush();
}
Server:
private int port;
public TestProgram(int port) {
this.port = port;
go();
}
public void go() {
ServerSocket ss = null;
ss = new ServerSocket(port);
while (true) {
Socket s = ss.accept();
new Handler(s).start();
}
}
What message are you trying to get? A random message or something preset? Are using a Gui?
IF your using a gui and your trying to get a message I'd expect you to do something like
JButton newButton = new JButton("New Message");
newButton.addActionListener(this);
this.add(newButton);
public void newMessage() {
System.out.println(in.readObject().toString);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource().equals(newButton)) {
newMessage();
}
}
Your Back End Client Could Look Something Like This
This is a sample so tear it apart and use what you'd like:
// Client.java: The client sends the input to the server and receives
// result back from the server
import java.io.*;
import java.net.*;
import java.util.*;
public class Client
{
// Main method
public static void main(String[] args)
{
// IO streams
DataOutputStream toServer;
DataInputStream fromServer;
try
{
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8000);
// Create input stream to receive data
// from the server
fromServer = new DataInputStream(socket.getInputStream());
// Create a output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
Scanner scan= new Scanner (System.in);
// Continuously send radius and receive area
// from the server
while (true)
{
// Read the m/s from the keyboard
System.out.print("Please enter a speed in meters per second: ");
double meters=scan.nextDouble();
// Send the radius to the server
toServer.writeDouble(meters);
toServer.flush();
// Convert string to double
double kilometersPerHour = fromServer.readDouble();
// Print K/h on the console
System.out.println("Area received from the server is "
+ kilometersPerHour);
}
}
catch (IOException ex)
{
System.err.println(ex);
}
}
}
Your Back End Server Should Look Something Like This
/*
* Created by jHeck
*/
// Server.java: The server accepts data from the client, processes it
// and returns the result back to the client
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
public class Server
{
// Main method
public static void main(String[] args)
{
try
{
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
// Start listening for connections on the server socket
Socket socket = serverSocket.accept();
// Create data input and output streams
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
// Continuously read from the client and process it,
// and send result back to the client
while (true)
{
// Convert string to double
double meters = inputFromClient.readDouble();
// Display radius on console
System.out.println("Meters received from client: "
+ meters);
// Compute area
double conversionToKilometers = (meters/1000)*3600;
// Send the result to the client
outputToClient.writeDouble(conversionToKilometers);
//Create double formater
DecimalFormat format = new DecimalFormat("0.00");
String formatedCTK = format.format(conversionToKilometers);
// Print the result to the console
System.out.println("Kilometers per hour = "+ formatedCTK);
}
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}

Client is unable to connect to server; an IOException is thrown. Simple client/server issue

I'm a beginner (as you can probably tell) and I'm having issues establishing a connection from my very simple client to my very simple server. My server starts up fine as it creates a serversocket that listens on port 43594. However, when I run my client to try to establish a connection, an IOException is thrown by my client as it tries to connect.
I'm doing java in my spare time as a hobby, so I'd really appreciate if someone could help me understand what's going on, where I'm going wrong (or if I'm even going right any where) so as to help me improve.
Here is my Server code:
package src.org;
import java.io.FileInputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.*;
import java.io.*;
public class Server {
private static final Logger logger = Logger.getLogger(Server.class.getName());
private final static void createSocket(int portNumber) throws IOException
{
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public static void main(String... args)
{
logger.info("Starting server...");
Properties properties = new Properties();
logger.info("loading settings...");
try
{
properties.load(new FileInputStream("settings.ini"));
Constants.GAME_NAME = properties.getProperty("name");
Constants.PORT = Integer.valueOf(properties.getProperty("port"));
} catch(Exception ex)
{
ex.printStackTrace();
}
logger.info("Creating sockets...");
try
{
logger.info("Socket created. Listening on port: " + Constants.PORT);
createSocket(Constants.PORT);
} catch(Exception ex)
{
logger.log(Level.SEVERE, "Error creating sockets.", ex);
System.exit(1);
}
}
}
Which (to my knowledge) seems to be doing its job.
And here's what I believe to be the culprit class, the client class:
import java.io.*;
import java.net.*;
public class Client {
//private static final String hostName = Constants.HOST_NAME;
//private static final int portNumber = Constants.PORT;
private static final String hostName = "localhost";
private static final int portNumber = 43594;
public static void main(String... args)
{
try (
Socket socket = new Socket(InetAddress.getLocalHost(), portNumber); // using localhost at the moment
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
System.out.println("Client socket created.");
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer, fromUser;
while((fromServer = in.readLine()) != null)
{
System.out.println("Server:" + fromServer);
fromUser = stdIn.readLine();
if(fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch(UnknownHostException ex) {
System.err.println("Unknown host: " + hostName);
System.exit(1);
} catch(IOException ioe) {
System.err.println("Couldn't get i/o from: " + hostName);
System.out.println("Error:" + ioe.getMessage());
System.exit(1);
}
}
}
When I ping localhost I get a response; the port on both sides is 43594 and the host is just local. The command line response from the client is:
Client socket created
Couldn't get i/o from: localhost
Error: connection reset
Press any key to continue...
I'm sorry in that I know this would be a very simple fix to many of you, but I can't seem to find an answer or fix it myself. Any insight or help would be greatly appreciated. Cheers.
Sorry if I've left out any other important pieces of information.
You've left out much of the code. The part in the server that sends data on the accepted socket. So the method that calls accept() just exits, the socket is garbage-collected, and closed, and the client keeps doing I/O to the other end of the connection, which is invalid,so you get an exception.

Categories