Created
October 23, 2013 02:38
-
-
Save anonymous/7111749 to your computer and use it in GitHub Desktop.
Test program to expose socket connection issues on Windows 8.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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