I am just learning how to use sockets, and I have managed to get my server to send a message to my socket, but when I try to send a message from my socket to my server I get an error. Here are my codes
Server:
package BasicNIO;
import java.io.*;
import java.net.*;
import java.nio.*;
public class ServerSockets {
ServerSocket servSock;
Socket sock;
public ServerSockets (){
// creates a new server socket at port 5555
try {
servSock = new ServerSocket (5555);
System.out.println("Server Started: " + servSock);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// creates a socket that uses the server socket
try {
sock = servSock.accept();
System.out.println("Client Connected: " + sock);
PrintStream ps = new PrintStream (sock.getOutputStream ());
ps.println ("Server: Hello"); // sends message
ps.close(); // closes print stream
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(" Connection from : " + sock.getInetAddress());
try {
DataInputStream is = new DataInputStream(sock.getInputStream());
System.out.println(is.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sock.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // closes socket connection
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSockets ss = new ServerSockets ();
}
}
Client:
package BasicNIO;
import java.io.*;
import java.net.*;
import java.nio.*;
public class Sockets {
Socket sock;
public Sockets (){
InetAddress ip;
try {
ip = InetAddress.getByName
("192.168.0.100");
sock = new Socket (ip,5555);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
PrintStream ps = new PrintStream(sock.getOutputStream());
ps.println ("Client: Hi Server");
DataInputStream is = new DataInputStream(sock.getInputStream());
String message = is.readLine();
System.out.println (message);
ps.close();
sock.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main (String [] args){
Sockets s = new Sockets ();
}
}
Thanks for any help.