Skip to content

Instantly share code, notes, and snippets.

Created October 23, 2013 02:38
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 anonymous/7111749 to your computer and use it in GitHub Desktop.
Save anonymous/7111749 to your computer and use it in GitHub Desktop.
Test program to expose socket connection issues on Windows 8.1
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketListener {
public static void main(String[] args) throws IOException {
int port;
if (args.length >= 1) {
port = Integer.parseInt(args[0]);
} else {
port = 0;
}
try (ServerSocket ss = new ServerSocket(port)) {
System.out.println("Bound socket on port " + ss.getLocalPort());
byte[] buffer = new byte[1024];
while (true) {
Socket conn = ss.accept();
System.out.println("Accepted new connection");
InputStream inputStream = conn.getInputStream();
while (true) {
int numBytes = inputStream.read(buffer);
if (numBytes < 0) {
System.out.println("Got socket closed notification");
break;
}
String read = new String(buffer, 0, numBytes);
System.out.println("Read " + numBytes + " bytes:");
System.out.println(read);
}
}
}
}
}
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketTalker {
public static void main(String[] args) throws UnknownHostException, IOException {
int port;
String host;
if (args.length >= 2) {
host = args[0];
port = Integer.valueOf(args[1]);
} else {
throw new IllegalArgumentException("Usage: java SocketTalker <host> <port>");
}
try (Socket sock = new Socket(host, port)) {
OutputStream os = sock.getOutputStream();
Writer w = new PrintWriter(os);
for (int i = 0; i < 10; i++) {
w.append("I am line " + (i+1) + " of text and I don't have too much to say but I'll keep on saying it anyway because I can.\n");
}
w.flush();
w.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment