Hi guys,
I'm trying to get a client and server talking together for some preperation for my final year project. I'm having a problem with my client, where it cannot create a socket even if the server is on the same PC. I was wondering if anyone could tell me what's wrong, and what code I should amend. I've done some debugging before asking on the forum, but I havn't been able to spot what's wrong, having looked at other client programs.
Basicly, the idea is for the client to send "Hello World" to the server, and the server to echo Hello World back once.
Here's my code:
Server:
import java.io.*;
import java.net.*;
public class Server
{
public static void main (String [] args) throws IOException
{
//server variables
ServerSocket serverSocket=null;
Socket ServerclientSocket=null;
String inputLine, outputLine;
String ipaddress=null;
int portnumber=45000;
ipaddress="127.0.0.1";
System.out.println("Starting server");
//begining of server code
try
{
serverSocket = new ServerSocket(portnumber);
}
catch (IOException e)
{
System.out.println("Could not listen on port:" + portnumber);
System.exit(-1);
}
System.out.println("Port listening");
try
{
ServerclientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.out.println("Accept failed: "+ portnumber);
System.exit(-1);
}
System.out.println("Socket listenning on " + portnumber);
PrintWriter Serverout = new PrintWriter(ServerclientSocket.getOutputStream(), true);
BufferedReader Serverin = new BufferedReader(new InputStreamReader(ServerclientSocket.getInputStream()));
//Establish connection with client
Talk connection = new Talk();
//end of server code
}
}
Talk:
import java.net.*;
import java.io.*;
public class Talk
{
public String processInput(String theInput)
{
String theOutput = null;
theOutput=theInput;
return theOutput;
}
}
Client:
import java.io.*;
import java.net.*;
class Client
{
public static void main (String [] args) throws IOException
{
int portnumber=45000;
String ipaddress="127.0.0.1";
Socket clientsocket=null;
PrintWriter clientoutput=null;
BufferedReader clientinput=null;
System.out.println("Starting client");
try
{
clientsocket=new Socket(ipaddress, portnumber);
}
catch (UnknownHostException e)
{
System.out.println("Cannot find "+ ipaddress);
System.exit(1);
}
catch (IOException e)
{
System.out.println("Cannot get I/O for "+ ipaddress);
System.exit(1);
}
String userinput="Hello World";
clientoutput=new PrintWriter(clientsocket.getOutputStream(), true);
clientoutput.println(userinput);
System.out.println("Writing socket complete");
clientinput=new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
System.out.println("echo" + clientinput.readLine());
clientoutput.close();
clientinput.close();
clientsocket.close();
}
}
Can anyone point out what's wrong?
Cheers,
Ben