Skip to content

Instantly share code, notes, and snippets.

@soimort
Created November 21, 2013 13:20
Show Gist options
  • Save soimort/7581464 to your computer and use it in GitHub Desktop.
Save soimort/7581464 to your computer and use it in GitHub Desktop.
import java.io.*;
import java.net.*;
public class ComTestServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket clientSocket = null;
ObjectInputStream in = null;
ObjectOutputStream out = null;
int serverPort = 8021;
String message = "";
// Establish connection
try {
serverSocket = new ServerSocket(serverPort);
} catch (IOException e) {
System.out.println("Could not listen on port " + serverPort);
System.exit(-1);
}
System.out.println("Listening on port " + serverPort);
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed");
System.exit(-1);
}
try {
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
} catch (IOException ioe) {
System.out.println("Failed in creating streams");
System.exit(-1);
}
// Receive message from Android client
try {
message = (String)in.readObject();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
// Print message
System.out.println("Message: " + message);
// Send message back to client
System.out.println("Sending back message: " + message);
try {
out.writeObject(new String(message));
} catch (IOException ex) {
ex.printStackTrace();
}
// Close connection
try {
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
System.out.println("Could not close");
System.exit(-1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment