Skip to content

Instantly share code, notes, and snippets.

@lizettepreiss
Last active June 15, 2016 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lizettepreiss/2985e07c95c5423763ec2bcaed3315a8 to your computer and use it in GitHub Desktop.
Save lizettepreiss/2985e07c95c5423763ec2bcaed3315a8 to your computer and use it in GitHub Desktop.
package preiss;
import java.io.*;
import java.net.*;
public class SocketListener extends Thread {
public static final int PORT_NUMBER = 4241;
protected Socket socket;
public static void main(String[] args) {
ServerSocket server = null;
try {
server = new ServerSocket(PORT_NUMBER);
while (true) {
new SocketListener(server.accept());
}
}
catch(IOException ex) {
System.out.println("Unable to start server or accept connections");
System.exit(1);
}
finally {
try {
server.close();
}
catch(IOException ex) {
// not much can be done: log the error
// exits since this is the end of main
}
}
}
private SocketListener(Socket socket) {
this.socket = socket;
start();
}
// the server services client requests in the run method
public void run() {
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
String replyString = this.message;
try {
byte[] b = wrap(replyString.getBytes()); //not necessary in general. was used for a project where the message lenght had to be sent in the message.
out.write(b);
out.flush();
out.close();
} catch (IOException e1) {
System.out.println(e1.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch(IOException ex) {
System.out.println("Unable to get streams from client");
}
finally {
try {
in.close();
out.close();
socket.close();
}
catch(IOException ex) {
// not much can be done: log the error
}
}
}
public byte[] wrap(byte[] msg) throws Exception {
int len = msg.length;
if (len > 65535) {
throw new IllegalArgumentException("Exceeds 65535 bytes.");
}
byte firstByte = (byte)(len >>> 8);
byte secondByte = (byte)len;
ByteArrayOutputStream baos = new ByteArrayOutputStream(len + 2);
baos.write(firstByte);
baos.write(secondByte);
baos.write(msg);
return baos.toByteArray();
}
String message=new String("<message>MessageContents</message>");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment