JAVAサンプル十五)ネットワークプログラミング
58991 ワード
15.1 IPアドレス
インスタンス270は、コンピュータ名およびIPアドレスを取得する
import java.net.InetAddress;
public class NetDemo_1 {
public static void main(String[] args) {
try {
InetAddress ind = InetAddress.getLocalHost();
System.out.println(ind);
} catch (Exception e) {
System.out.println(" !");
}
}
}
インスタンス271は、ウェブサイトのIPアドレスを取得する
import java.net.InetAddress;
import java.net.UnknownHostException;
public class NetDemo_2 {
public static void main(String[] args) {
try {
InetAddress ind = InetAddress.getByName("192.108.33.32");
System.out.println(ind.getHostName());
InetAddress ind1 = InetAddress.getByName("www.sina.com");
System.out.println(ind1);
} catch (UnknownHostException e) {
System.out.println(e);
}
}
}
インスタンス272は、2つのウェブサイトのホスト名が同じか否かを判断する
import java.net.InetAddress;
import java.net.UnknownHostException;
public class NetDemo_3 {
public static void main(String[] args) {
try {
// InetAddress
InetAddress ind = InetAddress.getByName("www.sohu.com");
InetAddress ind1 = InetAddress.getByName("sohu.com");
if (ind.equals(ind1)) {//
System.out.println(" !");
} else {
System.out.println(" 。"); //
}
} catch (UnknownHostException e) {
//
e.printStackTrace();
}
}
}
例273 IPのタイプをテストする
import java.net.InetAddress;
import java.net.UnknownHostException;
public class NetDemo_4 {
public static int getVersion(InetAddress ia) { //
byte[] b = ia.getAddress(); // , 。
if (b.length == 4) { // 4
return 4; // 4
} else if (b.length == 16) {
return 6;
} else {
return -1;
}
}
public static char getClass(InetAddress ia) { //
byte[] b = ia.getAddress(); // , 。
if (b.length != 4) { // 4
throw new IllegalArgumentException("no ipv6 address");//
}
int firstByte = b[0]; //
// if-else
if ((firstByte & 0x80) == 0) {
return 'A';
} else if ((firstByte & 0xc0) == 0x80) {
return 'B';
} else if ((firstByte & 0xe0) == 0xc0) {
return 'C';
} else if ((firstByte & 0xF0) == 0xE0) {
return 'D';
} else if ((firstByte & 0xF8) == 0xF0) {
return 'E';
} else {
return 'F';
}
}
public static void main(String[] args) {
InetAddress ia = null;
try {
ia = InetAddress.getByName("www.sina.com");//
} catch (UnknownHostException e) {
e.printStackTrace();
}
int len;
char king;
len = getVersion(ia); //
System.out.println(" :" + len);
king = getClass(ia); //
System.out.println(" :" + king);
}
}
インスタンス274ホストの検索
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class NetDemo_5 {
private static String lookup(String host) {
InetAddress ia;
byte[] b = null; // byte
try {
ia = InetAddress.getByName(host);
} catch (UnknownHostException e) {
return " !";
}
if (isHostName(host)) { //
String s = ""; //
for (int i = 0; i < b.length; i++) { //
int c = b[i] < 0 ? (b[i] + 256) : b[i];
s += c;
if (i != b.length - 1) {
s += ",";
}
}
return s; //
} else {
return ia.getHostName(); //
}
}
private static boolean isHostName(String host) { //
char[] ch = host.toCharArray(); // ,
for (int i = 0; i < ch.length; i++) {
if (!Character.isDigit(ch[i])) {
if (ch[i] != '.') {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
if (args.length > 0) {
for (int i = 0; i < args.length; i++) { //
System.out.println(lookup(args[i]));
}
} else {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out.println();
while (true) {
try {
String s = br.readLine();
if (s.equals("exit")) { // “exit” ,
break;
}
System.out.println(lookup(s));
} catch (IOException e) {
System.err.println(e);
}
}
}
}
}
インスタンス275ホストがサポートするプロトコル
15.2 URL類の使用
インスタンス276は、URLを使用してウェブページにアクセスする
import java.applet.Applet;
import java.awt.GridLayout;
import java.awt.Label;
import java.net.MalformedURLException;
import java.net.URL;
public class NetDemo_7 extends Applet{
public void init(){
URL url = this.getDocumentBase();
try {
URL url1 = new URL(url,"a.html"); // URL
this.setLayout(new GridLayout(2,1));//
//
this.add(new Label(url.toString()));
this.add(new Label(url1.toString()));
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
インスタンス277 URLのコンポーネント
import java.net.MalformedURLException;
import java.net.URL;
public class NetDemo_8 {
public static void main(String[] args){
for(int i=0;i<args.length;i++){
try {
URL url = new URL(args[i]);
System.out.println("URL :"+url);
System.out.println("URL :"+url.getProtocol());
System.out.println(" :"+url.getUserInfo());
String s = url.getHost();
if(s!=null){
int it = s.indexOf('@');
if(it!=-1){
s= s.substring(it+1);
System.out.println(s);
}
}else{
System.out.println(args[i]+" !");
}
System.out.println(" :"+url.getPort());
System.out.println(" :"+url.getPath());
System.out.println(" :"+url.getFile());
System.out.println(" :"+url.getHost());
} catch (MalformedURLException e) {
System.out.println(" URL !");
}
}
}
}
インスタンス278は、指定されたURLによってウェブページのソースコードを取得することができる
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
public class NetDemo_9 {
public static void main(String[] args) throws IOException{
if(args.length>0){
URL url;
try {
url = new URL(args[0]);
InputStream in = url.openStream();
in= new BufferedInputStream(in);
Reader r = new InputStreamReader(in);
int b;
while((b = r.read())!=-1){
System.out.print((char)b);
}
Object o = url.getContent();
System.out.println(o.getClass().getName());
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (Exception e) {
System.out.print(e);
}
}
}
}
例279一対のマルチ通信モード
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class MySocketServer { // Socket
public static void main(String[] args) { // java
try {
new StartServer(8080); //
} catch (Exception e) { //
System.out.println(" :" + e.getMessage());
}
}
}
class StartServer extends ServerSocket { // socket
private int port; //
public StartServer(int port) throws IOException {
super(port); // port
this.port = port;
System.out.println(" , :" + port);
System.out.println(" .........");
try {
while (true) { //
Socket socketCon = accept();
new RunServer(socketCon, port); //
}
} catch (IOException e) {
System.out.println(" ......");
} finally {
close(); //
}
}
}
class RunServer extends Thread { //
private int port; //
private Socket socketCon;
private BufferedReader in;
private PrintWriter out;
public RunServer(Socket s, int port) throws IOException {
this.port = port;
this.socketCon = s;
in = new BufferedReader(new InputStreamReader(socketCon
.getInputStream(), "gb2312")); //
// ,true:
out = new PrintWriter(socketCon.getOutputStream(), true);
out.println(" ........."); //
out.println(" quit ");
start(); //
}
public String infoUpperCase(String line) { //
return line.toUpperCase(); //
}
public void run() {
try {
boolean done = false;
while (!done) {
String line = in.readLine(); //
if (line == null)
done = true;
else { //
System.out.println(" :" + line);
String message = infoUpperCase(line); //
//
out.println(" :" + message);
if (line.trim().equals("quit")) //
done = true;
}
}
System.out.println(" ......");
socketCon.close(); //
} catch (Exception e) { //
System.out.println(" :" + e.getMessage());
}
}
}
/**-------- :MyOneClient.java-------------*/
class MyOneClient { // Socket
public static void main(String[] args) { // java
try {
new Client1("localhost", 8080); // IP , 8080
} catch (Exception e) { //
System.out.println(" :" + e.getMessage());
}
}
}
class PointClient { // Socket
private String host; // IP ( )
private int port; //
public PointClient(String host, int port) { //
this.host = host;
this.port = port;
connectServer(); //
}
public void connectServer() { //
try {
Socket socketConn; // Socket
// IP ( ) localhost
if (host.equals("localhost") || host.equals("127.0.0.1")) {
//
socketConn = new Socket(InetAddress.getLocalHost(), port);
} else { //
socketConn = new Socket(InetAddress.getByName(host), port);
}
BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in)); //
PrintWriter out = new PrintWriter(socketConn.getOutputStream(),
true); //
BufferedReader in = new BufferedReader(new InputStreamReader(
socketConn.getInputStream())); //
System.out.println(" :" + in.readLine()); //
System.out.println(" :" + in.readLine());
System.out.print(" >"); //
boolean done = false;
while (!done) {
String line = stdin.readLine(); //
out.println(line); //
if (line.equalsIgnoreCase("quit")) // quit
done = true;
String info = in.readLine(); //
System.out.println(" :" + info); //
if (!done) //
System.out.print(" >");
}
socketConn.close(); //
} catch (SecurityException e) { //
System.out.println(" !");
} catch (IOException e) { // IO
System.out.println(" I/O !");
}
}
}
/**-------- :MyTwoClient.java-------------*/
class MyTwoClient { // Socket
public static void main(String[] args) { // java
try {
new Client1("localhost", 8080); // IP , 80
} catch (Exception e) { //
System.out.println(" :" + e.getMessage());
}
}
}
class Client1 { // Socket
private String host; // IP ( )
private int port; //
public Client1(String host, int port) { //
this.host = host;
this.port = port;
connectServer(); //
}
public void connectServer() { //
try {
Socket socketConn; // Socket
// IP ( ) localhost
if (host.equals("localhost") || host.equals("127.0.0.1")) {
//
socketConn = new Socket(InetAddress.getLocalHost(), port);
} else { //
socketConn = new Socket(InetAddress.getByName(host), port);
}
BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in)); //
PrintWriter out = new PrintWriter(socketConn.getOutputStream(),
true); //
BufferedReader in = new BufferedReader(new InputStreamReader(
socketConn.getInputStream())); //
System.out.println(" :" + in.readLine()); //
System.out.println(" :" + in.readLine());
System.out.print(" >"); //
boolean done = false;
while (!done) {
String line = stdin.readLine(); //
out.println(line); //
if (line.equalsIgnoreCase("quit")) // quit
done = true;
String info = in.readLine(); //
System.out.println(" :" + info); //
if (!done) //
System.out.print(" >");
}
socketConn.close(); //
} catch (SecurityException e) { //
System.out.println(" !");
} catch (IOException e) { // IO
System.out.println(" I/O !");
}
}
}
インスタンス280自作ブラウザ
import java.awt.event.WindowEvent;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
//
class LinkFollower implements HyperlinkListener{
private JEditorPane jep;
public LinkFollower(JEditorPane jep){
this.jep= jep;
}
public void hyperlinkUpdate(HyperlinkEvent he){
if(he.getEventType()==HyperlinkEvent.EventType.ACTIVATED){
try {
jep.setPage(he.getURL());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class NetDemo_15{
public static void main(String[] args){
String initPage = "http://www.sina.com";
if(args.length>0){
initPage = args[0];
JEditorPane jep = new JEditorPane();
jep.setEditable(false);
jep.addHyperlinkListener(new LinkFollower(jep));
try {
jep.setPage(initPage);
} catch (IOException e) {
e.printStackTrace();
}
JScrollPane jsp = new JScrollPane(jep);
JFrame jf = new JFrame(" ");
jf.setDefaultCloseOperation(WindowEvent.COMPONENT_SHOWN);
jf.getContentPane().add(jsp);
jf.setSize(512,324);
jf.show();
}
}
}
例281スキャンTCPポート
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class NetDemo_16 {
public static void main(String[] args){
String str = "localhost";
if(args.length>0){
str = args[0];
}
for(int i=100;i<500;i++){ //
try {
Socket s = new Socket();
System.out.println("There is a server on"+i+"of"+s);
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
}
インスタンス282 TCPプロトコルサーバ
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPSocketServer {
public static void main(String[] args) { // java
try {
Server server = new Server(8080); //
} catch (Exception e) { //
System.out.println(" :" + e.getMessage());
}
}
}
class Server { // Socket
private int port; //
public Server(int port) { //
this.port = port;
start(); //
}
public String infoUpperCase(String line) { //
return line.toUpperCase(); //
}
public void start() { //
try {
// Socket
ServerSocket serverSocket = new ServerSocket(port);
//
System.out.println(" , :" + port);
System.out.println(" .........");
//
Socket socketAccept = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
socketAccept.getInputStream())); //
// ,true:
PrintWriter out = new PrintWriter(socketAccept.getOutputStream(),
true);
out.println(" ........."); //
out.println(" quit ");
boolean done = false;
while (!done) {
String line = in.readLine(); //
if (line == null) { //
done = true;
} else {
//
System.out.println(" :" + line);
//
String message = infoUpperCase(line);
//
out.println(" :" + message);
if (line.trim().equals("quit")) //
done = true;
}
}
socketAccept.close(); //
} catch (Exception e) { //
System.out.println(" :" + e.getMessage());
}
}
}
例283 TCPプロトコルクライアント
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class TCPSocketClient {
public static void main(String[] args) { // java
try {
new Client("localhost", 8080); // IP , 80
} catch (Exception e) { //
System.out.println(" :" + e.getMessage());
}
}
}
class Client { // Socket
private String host; // IP ( )
private int port; //
public Client(String host, int port) { //
this.host = host;
this.port = port;
connectServer(); //
}
public void connectServer() { //
try {
Socket socketConn; // Socket
// IP ( ) localhost
if (host.equals("localhost") || host.equals("127.0.0.1")) {
// Socket
socketConn = new Socket(InetAddress.getLocalHost(), port);
} else { // Socket
socketConn = new Socket(InetAddress.getByName(host), port);
}
BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in)); //
PrintWriter out = new PrintWriter(socketConn.getOutputStream(),
true); //
BufferedReader in = new BufferedReader(new InputStreamReader(
socketConn.getInputStream()));//
//
System.out.println(" :" + in.readLine());
System.out.println(" :" + in.readLine());
System.out.print(" >"); //
boolean done = false;
while (!done) {
String line = stdin.readLine(); //
out.println(line); //
if (line.equalsIgnoreCase("quit")) // quit
done = true;
String info = in.readLine(); //
System.out.println(" :" + info); //
if (!done) //
System.out.print(" >");
}
socketConn.close(); //
} catch (SecurityException e) { //
System.out.println(" !");
} catch (IOException e) { // IO
System.out.println(" I/O !");
}
}
}
インスタンス284ソケット接続情報
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class NetDemo_17 {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
try {
Socket s = new Socket(args[i], 80);
System.out.println("Connected to" + s.getInetAddress()
+ "on port" + s.getPort() + "from port"
+ s.getLocalPort() + "of" + s.getLocalAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
インスタンス285 Echoサービスのクライアントはどのように実装されますか?
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoClient {
public static void main(String args[]) {
try {
Socket connection = new Socket("", 7);// Socket ,Echo 7 System.out.println(" :");
DataInputStream in = new DataInputStream(connection
.getInputStream());// Socket
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());// Socket
String line = new String("");
while (!line.toUpperCase().equals(".QUIT")) {
System.out.println(" : ");
line = EchoClient.readString();//
System.out.println("\t ...");
out.writeUTF(line);// UTF
System.out.println("\t ...");
line = in.readUTF();// UTF
System.out.println("Received: " + line);//
}
in.close();
out.close();
connection.close();
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + args[0]);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
public static String readString() {
String string = new String();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));//
try {
string = in.readLine();
} catch (IOException e) {
}
return string;
}
}
インスタンス286は、ネイティブのサービスポートを検出する
import java.io.IOException;
import java.net.ServerSocket;
public class usrLocalPostScanner {
public static void main(String[] args) {
//
for (int port = 1; port <= 65535; port++) {
try {
//
// ,
ServerSocket server = new ServerSocket(port);
} catch (IOException e) {
//
System.out.println("There is a server on port " + port + ".");
}
}
}
}
インスタンス287でダウンロードしたページはリンクを失わない
import java.net.URLEncoder;
//
public class NetDemo_11 {
public static void main(String[] args){
System.out.println(URLEncoder.encode("This string has spaces"));
System.out.println(URLEncoder.encode("This*string*has*asterisks"));
System.out.println(URLEncoder.encode("This%string%has%persent%signs"));
System.out.println(URLEncoder.encode("This+string+has+pulses"));
System.out.println(URLEncoder.encode("This/string/has/slashes"));
System.out.println(URLEncoder.encode("This:string:has:colors"));
System.out.println(URLEncoder.encode("This-string-has-tildes"));
System.out.println(URLEncoder.encode("This(string)has(parentheses)"));
System.out.println(URLEncoder.encode("This.string.has.periods"));
System.out.println(URLEncoder.encode("This&string&has&ersands"));
}
}
インスタンス288は、ウェブページを再配向する方法
import java.applet.Applet;
import java.net.MalformedURLException;
import java.net.URL;
//
public class NetDemo_12 extends Applet{
public void init(){
try {
getAppletContext().showDocument(new URL("http://delfault.myetang.com"),"_blank");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
インスタンス289はインターネット上でオブジェクトを検索する
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
// Intenet
public class NetDemo_13 {
public static void main(String[] args) throws IOException{
String target = "";
for(int i=0;i<args.length;i++){
target +=args[i]+"";
}
target= target.trim();
URL url;
try {
url = new URL("http://www.baidu.com/");
InputStream in = new BufferedInputStream(url.openStream());
InputStreamReader isr = new InputStreamReader(in);
int b;
while((b= isr.read())!=-1){
System.out.print((char)(b));
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
インスタンス290 LAN使用プロキシサーバ
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.net.ServerSocket;
import java.net.Socket;
public class LANProxy extends Thread { //
protected Socket socket; // Socket
private static String parent = null; //
private static int parentPort = -1;
public static int RETRIES = 5; //
public static int PAUSE = 5; //
public static int TIMEOUT = 50; // Socket
public static int BUFSIZ = 1024; //
public static boolean logging = false; //
public static OutputStream log = null; // OutputStream
public void run() { //
String line;
String host;
int port = 80;
Socket outbound = null;
try {
socket.setSoTimeout(TIMEOUT); //
InputStream is = socket.getInputStream(); //
OutputStream os = null;
try {
line = ""; //
host = "";
int state = 0;
boolean space;
while (true) { //
int c = is.read(); //
if (c == -1) //
break;
if (logging)
proxyLog(c, true); //
space = Character.isWhitespace((char) c);//
switch (state) { //
case 0:
if (space)
continue; //
state = 1; //
case 1:
if (space) {
state = 2;
continue; //
}
line = line + (char) c; //
break;
case 2:
if (space)
continue; //
state = 3; //
case 3:
if (space) { //
state = 4; //
String host0 = host; //
int n;
n = host.indexOf("//"); // ( )
if (n != -1) //
host = host.substring(n + 2);
n = host.indexOf('/');
if (n != -1) // /
host = host.substring(0, n);
n = host.indexOf(":"); //
if (n != -1) { // :
port = Integer.parseInt(host.substring(n + 1));
host = host.substring(0, n);
}
host = outLog(host0, host, port, socket);//
if (parent != null) {
host = parent;
port = parentPort;
}
int retry = RETRIES;
while (retry-- != 0) {
try { //
outbound = new Socket(host, port);
break;
} catch (Exception e) {
System.out.println(" :"
+ e.getMessage());
}
Thread.sleep(PAUSE); //
}
if (outbound == null)
break;
outbound.setSoTimeout(TIMEOUT); //
os = outbound.getOutputStream(); //
os.write(line.getBytes()); //
os.write(' ');
os.write(host0.getBytes()); //
os.write(' ');
outInfo(is, outbound.getInputStream(), os, socket
.getOutputStream()); //
break;
}
host = host + (char) c;
break;
}
}
} catch (IOException e) {
}
} catch (Exception e) {
} finally {
try {
socket.close(); //
} catch (Exception e1) {
}
try {
outbound.close();
} catch (Exception e2) {
}
}
}
void outInfo(InputStream is0, InputStream is1, OutputStream os0,
OutputStream os1) throws IOException { //
try {
int ir;
byte bytes[] = new byte[BUFSIZ]; // , :1024
while (true) {
try {
if ((ir = is0.read(bytes)) > 0) { //
os0.write(bytes, 0, ir); //
if (logging)
proxyLog(bytes, 0, ir, true); //
} else if (ir < 0) //
break;
} catch (InterruptedIOException e) { // IO
}
try {
if ((ir = is1.read(bytes)) > 0) { //
os1.write(bytes, 0, ir); //
if (logging)
proxyLog(bytes, 0, ir, false); //
} else if (ir < 0) //
break;
} catch (InterruptedIOException e) { // IO
}
}
} catch (Exception e0) { //
}
}
// ( )。
public static void setProxy(String name, int port) {
parent = name;
parentPort = port;
}
public LANProxy(Socket s) { //
socket = s;
start(); //
}
public void proxyLog(int c, boolean browser) throws IOException { //
log.write(c);
}
public void proxyLog(byte[] bytes, int offset, int len, boolean browser)
throws IOException { //
for (int i = 0; i < len; i++)
proxyLog((int) bytes[offset + i], browser);
}
// ,
public String outLog(String url, String host, int port, Socket sock) {
java.text.DateFormat cal = java.text.DateFormat.getDateTimeInstance();
System.out.println(cal.format(new java.util.Date()) + " - " + url + " "
+ sock.getInetAddress() + "
");
return host;
}
public static void startProxy(int port, Class clobj) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(port); // Socket
while (true) {
Class[] objClass = new Class[1]; // , 1
Object[] obj = new Object[1]; // , 1
objClass[0] = Socket.class; // Socket
try { //
Constructor cons = clobj.getDeclaredConstructor(objClass);
obj[0] = serverSocket.accept(); //
cons.newInstance(obj); // HttpProxy
} catch (Exception e) {
Socket socket = (Socket) obj[0];//
try {
socket.close(); //
} catch (Exception ec) {
}
}
}
} catch (IOException e) {
}
}
public static void main(String args[]) { // java
System.out.println("LAN ......");
LANProxy.log = System.out; //
LANProxy.logging = false;
LANProxy.startProxy(8080, LANProxy.class);//
}
}
例291 BBSフォーラムサーバ側
package net;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.TitledBorder;
/**
* ,GUI
*/
public class BBSServer extends JFrame {
static JLabel statusBar = new JLabel(); //
//
static java.awt.List connectInfoList = new java.awt.List(10);
//
static Vector clientProcessors = new Vector(10);
//
static int activeConnects = 0;
//
public BBSServer() {
init();
try {
//
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
e.printStackTrace();
}
}
private void init() {
this.setTitle("BBS 1 ");
statusBar.setText("");
//
JMenu fileMenu = new JMenu();
fileMenu.setText(" ");
JMenuItem exitMenuItem = new JMenuItem();
exitMenuItem.setText(" ");
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exitActionPerformed(e);
}
});
fileMenu.add(exitMenuItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
//
JPanel jPanel1 = new JPanel();
jPanel1.setLayout(new BorderLayout());
JScrollPane pane = new JScrollPane(connectInfoList);
pane.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.red, new Color(134, 134, 0)), " IP "));
jPanel1.add(new JScrollPane(pane), BorderLayout.CENTER);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(statusBar, BorderLayout.SOUTH);
this.getContentPane().add(jPanel1, BorderLayout.CENTER);
this.pack();
}
/** */
public void exitActionPerformed(ActionEvent e) {
//
sendMsgToClients(new StringBuffer(Message.QUIT_IDENTIFER));
closeAll(); //
System.exit(0);
}
/** */
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
exitActionPerformed(null);
}
}
/** , clientProcessors, */
public static void RefreshRoom() {
StringBuffer people = new StringBuffer(Message.PEOPLE_IDENTIFER);
for (int i = 0; i < clientProcessors.size(); i++) {
MessFromClient c = (MessFromClient) clientProcessors.elementAt(i);
people.append(Message.SEPERATOR).append(c.clientName);
}
// sendClients
sendMsgToClients(people);
}
/** */
public static synchronized void sendMsgToClients(StringBuffer msg) {
for (int i = 0; i < clientProcessors.size(); i++) {
MessFromClient c = (MessFromClient) clientProcessors.elementAt(i);
System.out.println("send msg: " + msg);
c.send(msg);
}
}
/** */
public static void closeAll() {
while (clientProcessors.size() > 0) {
MessFromClient c = (MessFromClient) clientProcessors.firstElement();
try {
// socket
c.socket.close();
c.toStop();
} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
clientProcessors.removeElement(c);
}
}
}
/**
* 。 , IP 。
*/
public static boolean isCheck(MessFromClient newclient) {
if (clientProcessors.contains(newclient)) {
return false;
} else {
return true;
}
}
/**
* ,
*/
public static void disconnect(MessFromClient client) {
disconnect(client, true);
}
/**
* ,
*/
public static synchronized void disconnect(MessFromClient client,
boolean toRemoveFromList) {
try {
// list
connectInfoList.add(client.clientIP + " ");
BBSServer.activeConnects--; // 1
String constr = " :" + BBSServer.activeConnects + " ";
statusBar.setText(constr);
//
client.send(new StringBuffer(Message.QUIT_IDENTIFER));
client.socket.close();
} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
// clients socket , 。
if (toRemoveFromList) {
clientProcessors.removeElement(client);
client.toStop();
}
}
}
public static void main(String[] args) {
BBSServer chatServer1 = new BBSServer();
chatServer1.setVisible(true);
System.out.println("Server starting ...");
ServerSocket server = null;
try {
//
server = new ServerSocket(Message.SERVER_PORT);
} catch (IOException e) {
System.out.println("Error:" + e);
System.exit(1);
}
while (true) {
// MAX_CLIENT
if (clientProcessors.size() < Message.MAX_CLIENT) {
Socket socket = null;
try {
//
socket = server.accept();
if (socket != null) {
System.out.println(socket + " ");
}
} catch (IOException e) {
System.out.println("Error:" + e);
}
// ClientProcessor ,
MessFromClient c = new MessFromClient(socket);
if (isCheck(c)) {
clientProcessors.addElement(c); //
int connum = ++BBSServer.activeConnects; // ,
//
String constr = " :" + connum + " ";
BBSServer.statusBar.setText(constr);
// socket list
BBSServer.connectInfoList.add(c.clientIP + " ");
c.start();
RefreshRoom(); //
} else {
//
c.ps.println(" ");
disconnect(c, false);
}
} else {
// MAX_CLIENT ,
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
}
}
}
}
/**
*
*/
class MessFromClient extends Thread {
Socket socket; // socket
String clientName; //
String clientIP; // ip
BufferedReader br; //
PrintStream ps; //
boolean running = true;
/** */
public MessFromClient(Socket s) {
socket = s;
try {
//
br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
ps = new PrintStream(socket.getOutputStream());
// , 、IP
String clientInfo = br.readLine();
// ,
StringTokenizer stinfo = new StringTokenizer(clientInfo,
Message.SEPERATOR);
String head = stinfo.nextToken();
if (head.equals(Message.CONNECT_IDENTIFER)) {
if (stinfo.hasMoreTokens()) {
//
clientName = stinfo.nextToken();
}
if (stinfo.hasMoreTokens()) {
// ip
clientIP = stinfo.nextToken();
}
System.out.println(head); //
}
} catch (IOException e) {
System.out.println("Error:" + e);
}
}
/** */
public void send(StringBuffer msg) {
ps.println(msg);
ps.flush();
}
//
public void run() {
while (running) {
String line = null;
try {
//
line = br.readLine();
} catch (IOException e) {
System.out.println("Error" + e);
BBSServer.disconnect(this);
BBSServer.RefreshRoom();
return;
}
//
if (line == null) {
BBSServer.disconnect(this);
BBSServer.RefreshRoom();
return;
}
StringTokenizer st = new StringTokenizer(line, Message.SEPERATOR);
String keyword = st.nextToken();
// MSG
if (keyword.equals(Message.MSG_IDENTIFER)) {
StringBuffer msg = new StringBuffer(Message.MSG_IDENTIFER)
.append(Message.SEPERATOR);
msg.append(clientName);
msg.append(st.nextToken("\0"));
//
BBSServer.sendMsgToClients(msg);
} else if (keyword.equals(Message.QUIT_IDENTIFER)) {
// QUIT
BBSServer.disconnect(this); //
// list
BBSServer.RefreshRoom();
running = false;
}
}
}
public void toStop() {
running = false;
}
// Object equals
public boolean equals(Object obj) {
if (obj instanceof MessFromClient) {
MessFromClient obj1 = (MessFromClient) obj;
if (obj1.clientIP.equals(this.clientIP)
&& (obj1.clientName.equals(this.clientName))) {
return true;
}
}
return false;
}
// Object hashCode
public int hashCode() {
return (this.clientIP + Message.SEPERATOR + this.clientName).hashCode();
}
}
package net;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.border.TitledBorder;
/**
* ,GUI 。
*/
public class BBSClient extends JFrame implements ActionListener {
//
JLabel nameLabel = new JLabel();
JTextField nameTextField = new JTextField(15);
//
JButton connectButton = new JButton();
JButton disConnectButton = new JButton();
JTextArea chatContentTextArea = new JTextArea(9, 30); //
JButton sendMsgButton = new JButton(); //
JTextField msgTextField = new JTextField(20); //
JLabel msglabel = new JLabel();
java.awt.List peopleList = new java.awt.List(10); //
/** */
Socket soc = null;
PrintStream ps = null;
//
ListenClentThread listener = null;
public BBSClient() {
init();
}
//
public void init() {
this.setTitle(" 1 ");
//
nameLabel.setText(" :");
connectButton.setText(" ");
connectButton.addActionListener(this);
disConnectButton.setText(" ");
disConnectButton.addActionListener(this);
//
chatContentTextArea.setEditable(false);
sendMsgButton.setText(" ");
sendMsgButton.addActionListener(this);
msgTextField.setText("");
// panel1
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout());
panel1.add(nameLabel);
panel1.add(nameTextField);
panel1.add(connectButton);
panel1.add(disConnectButton);
//
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
JScrollPane pane1 = new JScrollPane(chatContentTextArea);
pane1.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(134, 134, 134)), " "));
panel2.add(pane1);
JScrollPane pane2 = new JScrollPane(peopleList);
pane2.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(134, 134, 134)), " "));
panel2.add(pane2);
//
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
panel3.add(msglabel);
panel3.add(msgTextField);
panel3.add(sendMsgButton);
//
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(panel1, BorderLayout.NORTH);
this.getContentPane().add(panel2, BorderLayout.CENTER);
this.getContentPane().add(panel3, BorderLayout.SOUTH);
this.pack();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
e.printStackTrace();
}
}
/** */
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
// ,
disconnect();
dispose();
System.exit(0);
}
}
/** */
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == connectButton) {
//
if (soc == null) {
try {
// 2525
soc = new Socket(InetAddress.getLocalHost(),
Message.SERVER_PORT);
System.out.println(soc); //
ps = new PrintStream(soc.getOutputStream());// ps soc
//
StringBuffer info = new StringBuffer(
Message.CONNECT_IDENTIFER)
.append(Message.SEPERATOR);
// INFO
// name ip ":" ,
// StringTokenizer
String userinfo = nameTextField.getText()
+ Message.SEPERATOR
+ InetAddress.getLocalHost().getHostAddress();
ps.println(info.append(userinfo));
ps.flush();
// ,
listener = new ListenClentThread(this, nameTextField
.getText(), soc);
listener.start();
} catch (IOException e) {
System.out.println("Error:" + e);
disconnect();
}
}
} else if (source == disConnectButton) {
//
disconnect();
} else if (source == sendMsgButton) {
//
if (soc != null) {
//
StringBuffer msg = new StringBuffer(Message.MSG_IDENTIFER)
.append(Message.SEPERATOR);
//
ps.println(msg.append(msgTextField.getText()));
ps.flush();
}
}
}
/** */
public void disconnect() {
if (soc != null) {
try {
// QUIT
ps.println(Message.QUIT_IDENTIFER);
ps.flush();
soc.close(); //
listener.toStop();
soc = null;
} catch (IOException e) {
System.out.println("Error:" + e);
}
}
}
public static void main(String[] args) {
BBSClient client = new BBSClient();
client.setVisible(true);
}
/** */
class ListenClentThread extends Thread {
String name = null; // name
BufferedReader br = null; //
PrintStream ps = null; //
Socket socket = null; // socket
BBSClient parent = null; // ChatClient
boolean running = true;
//
public ListenClentThread(BBSClient p, String n, Socket s) {
//
parent = p;
name = n;
socket = s;
try {
//
br = new BufferedReader(new InputStreamReader(s
.getInputStream()));
ps = new PrintStream(s.getOutputStream());
} catch (IOException e) {
System.out.println("Error:" + e);
parent.disconnect();
}
}
//
public void toStop() {
this.running = false;
}
//
public void run() {
String msg = null;
while (running) {
msg = null;
try {
//
msg = br.readLine();
System.out.println("receive msg: " + msg);
} catch (IOException e) {
System.out.println("Error:" + e);
parent.disconnect();
}
//
if (msg == null) {
parent.listener = null;
parent.soc = null;
parent.peopleList.removeAll();
running = false;
return;
}
// StringTokenizer
StringTokenizer st = new StringTokenizer(msg, Message.SEPERATOR);
//
String keyword = st.nextToken();
if (keyword.equals(Message.PEOPLE_IDENTIFER)) {
// PEOPLE
//
parent.peopleList.removeAll();
// st
while (st.hasMoreTokens()) {
String str = st.nextToken();
parent.peopleList.add(str);
}
} else if (keyword.equals(Message.MSG_IDENTIFER)) {
// MSG ,
//
String usr = st.nextToken();
parent.chatContentTextArea.append(usr);
parent.chatContentTextArea.append(st.nextToken("\0"));
parent.chatContentTextArea.append("\r
");
} else if (keyword.equals(Message.QUIT_IDENTIFER)) {
// QUIT ,
System.out.println("Quit");
try {
running = false;
parent.listener = null;
parent.soc.close();
parent.soc = null;
} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
parent.soc = null;
parent.peopleList.removeAll();
}
break;
}
}
//
parent.peopleList.removeAll();
}
}
}
インスタンス292 UDPメッセージの送信と受信
import java.io.File;
import java.io.FileInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**-------- :UDPServer.java-------------*/
public class UDPServer {
public static void main(String args[]) {
try {
System.out.println("UDP , ...");
if (args.length != 1) {
throw new IllegalArgumentException(" ");
}
int port = Integer.parseInt(args[0]); //
// socket, 。
DatagramSocket dsocket = new DatagramSocket(port);
byte[] buffer = new byte[2048]; // UDP
// DatagramPacket, buffer 。
// , , UDP 2048 ,
//
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// ,
while (true) {
dsocket.receive(packet); //
// 。
String msg = new String(buffer, 0, packet.getLength());
//
System.out.println("Receive: "
+ packet.getAddress().getHostAddress() + ": " + msg);
// QUIT , 。
if (msg.equalsIgnoreCase("QUIT")) {
System.out.println(" UDP ");
break;
}
packet.setLength(buffer.length); //
}
// socket
dsocket.close();
} catch (Exception e) {
System.err.println(e);
// System.err.println(usage);
}
}
}
/**-------- :UDPClient.java-------------*/
class UDPClient {
public static void main(String args[]) {
try {
//
if (args.length < 3) {
throw new IllegalArgumentException(" ");
}
//
String host = args[0];
int port = Integer.parseInt(args[1]);
//
byte[] message;
if (args[2].equals("-f")) {
// -f, UDP
//
File f = new File(args[3]);
int len = (int) f.length();
//
message = new byte[len];
FileInputStream in = new FileInputStream(f);
//
int bytes_read = 0, n;
do {
n = in.read(message, bytes_read, len - bytes_read);
bytes_read += n;
} while ((bytes_read < len) && (n != -1));
} else {
// -f,
String msg = args[2];
for (int i = 3; i < args.length; i++) {
msg += " " + args[i];
}
message = msg.getBytes();
}
// IP
InetAddress address = InetAddress.getByName(host);
// UDP 。
// DatagramPacket InetAddress, IP
DatagramPacket packet = new DatagramPacket(message, message.length,
address, port);
// DatagramSocket, UDP
DatagramSocket dsocket = new DatagramSocket();
dsocket.send(packet);
System.out.println("send: " + new String(message));
dsocket.close();
// : DatagramPacket , IP ,
// DatagramSocket connect , UDP
packet = new DatagramPacket(message, message.length);
dsocket = new DatagramSocket();
dsocket.connect(address, port);
dsocket.send(packet);
System.out.println("Send: " + new String(message));
dsocket.close();
} catch (Exception e) {
System.err.println(e);
}
}
}