[戻る]

31---使用しているマシンのIPアドレスとホストネームを調べる。

/*
    
    
   */
//IPアドレス確認用フレーム
/* jarファイル作成コマンド
%JAVA_HOME%\bin\jar cmvf frame31.txt frame31.jar frame31.class
*/
import java.awt.*; 		//TextFieldなど利用のため
import java.net.*;		//InetAddress利用のため
import java.awt.event.*;//WindowListener利用のため
import java.lang.*;		//Exception利用のため

public class frame31 extends Frame implements WindowListener {
	TextArea  errtxt;
	TextArea  msgtxt;
	String nameHost;
	public static void main(String arg[]){
		new frame31();
	}
	
	public frame31(){//アプレットがロードされた時に呼ばれる。

		try {
			add(errtxt = new TextArea(2,60), BorderLayout.SOUTH); // エラーメッセージ用
			add(msgtxt = new TextArea(8,60), BorderLayout.CENTER); // 結果表示メッセージ用
			
			InetAddress localhost = InetAddress.getLocalHost();
			nameHost = localhost.getHostName();
			msgtxt.append("host Name:" + nameHost + "\n");
			
			InetAddress inets[] = InetAddress.getAllByName(nameHost);
			for(int i = 0; i < inets.length; i++){
				String number = new java.text.DecimalFormat("###.").format(i);
				msgtxt.append(number + "個目  ");
				msgtxt.append(inets[i].getHostAddress() + "   [");
				msgtxt.append(inets[i].getHostName() + "]\n");
			}

			addWindowListener(this);//ウィンドウイベント処理インスタンス登録
			pack();
			show();	//表示
		} 
		catch (UnknownHostException e){
			errtxt.append(e.toString());
		}
	}
	public void windowOpened(WindowEvent e) {}	//最初に起動する
	public void windowClosed(WindowEvent e) {} //クローズされた
	public void windowClosing(WindowEvent e) {
		this.dispose();	//クローズのプログラム 
	}
	public void windowIconified(WindowEvent e) {}//最小化
	public void windowDeiconified(WindowEvent e) {}//通常へ戻った
	public void windowActivated(WindowEvent e) {}//アクティブ化 
	public void windowDeactivated(WindowEvent e) {}//アクティブでなくなった 
}

[戻る]

32 ---UDP利用の送受信フレームプログラム

/*
    
    
   */
//   UDP送受信(ピア・ツー・ピア(Peer to Peer : P2P)のチャット)
/* jarファイル作成コマンド
%JAVA_HOME%\bin\jar cmvf frame32.txt frame32.jar frame32.class

frame32.txtの内容
Main-Class: frame32
Class-Path: .
*/
import java.awt.*; 		//TextFieldなど利用のため
import java.awt.event.*; //ActionListenerなど利用のため
import java.net.*;//InetAddress利用のため
import java.lang.*;		//Exception利用のため

public class frame32 extends Frame implements ActionListener, Runnable,WindowListener{
	Button btn;		//送信ボタン用
	TextArea msg;		//メッセージ表示用
	TextField txtRecPort;	//受信ポート
	TextField txtSndIp; 	//送信先IP用
	TextField txtSndPort; 	//送信先port用
	TextField txtSndMsg; 	//送信先port用
	Thread thread = null;	//受信ループスレッド
	DatagramSocket socket;	//受信用ソケット
	
	public frame32(){
		setTitle("UDPによる送受信実験");
		init();
		setSize(480,150);
		show();
	}
	
	public static void main(String argv[]){
		frame32 frm = new frame32();
	}
	
	public void init(){//アプレットがロードされた時に呼ばれる。
		setLayout(new BorderLayout());
		//各種メッセージ表示用
		add(msg = new TextArea(5,60),BorderLayout.CENTER);
		
		//上部配置
		Panel panel;
		add(panel = new Panel(),BorderLayout.NORTH); //上に配置のパネル
		try {
			InetAddress local = InetAddress.getLocalHost(); 
			panel.add(new Label("IP[" + local.getHostAddress() + "]"));
			panel.add(new Label(" Host Name[" + local.getHostName() + "]"));
			panel.add(txtRecPort = new TextField("9871"));
		} 
		catch (UnknownHostException e){
			msg.append(e.toString());
		}
		
		//下位配置
		add(panel = new Panel(),BorderLayout.SOUTH); //上に配置のパネル
		panel.add(new Label("ip"));
		panel.add(txtSndIp = new TextField("192.168.0.10"));
		panel.add(new Label("port"));
		panel.add(txtSndPort = new TextField("9871"));
		panel.add(new Label("msg"));
		panel.add(txtSndMsg = new TextField("abcdefgあいう123"));
		panel.add(btn = new Button("送信"));
		btn.addActionListener(this);//ボタン操作オブジェクト登録
		thread = new Thread(this);
		thread.start();
		this.addWindowListener(this);//ウインドウ操作オブジェクト登録
	}
	public void actionPerformed(ActionEvent e){ //送信ボタン処理
		try {
			InetAddress sendIp = InetAddress.getByName(txtSndIp.getText());
			DatagramSocket sendSocket = new DatagramSocket();	//ソケット生成

			
			//送信用パケット準備(このパケットに送信先IPや、ポート番号もセットする仕様)
			byte [] bufmsg = txtSndMsg.getText().getBytes();
			int port = Integer.parseInt(txtSndPort.getText());
			DatagramPacket packet = new DatagramPacket(bufmsg, bufmsg.length,sendIp,port);
			
			//送信
			sendSocket.send(packet);
			sendSocket.close();
		} catch(Exception es){
			System.out.println(es);
		}
	}
	
	public void run(){//受信処理のスレッド
		try {
			socket = new DatagramSocket(Integer.parseInt(txtSndPort.getText()));//ソケットの生成
		}
		catch(SocketException e){
			msg.append("DatagramSocket :" + e.toString());
			return;
		}
		while(this.thread != null){
			try {
				byte [] bufmsg = new byte[100];//受信パケットの準備
				DatagramPacket	packet = new DatagramPacket(bufmsg, bufmsg.length); //受信用のパケット生成(2byte用)
			
				//パケット受信
				socket.receive(packet);
				msg.append(new String(packet.getData()));//受信データ表示
				
			}catch(Exception e){
				msg.append(e.toString());
				//ソケットクローズ
				socket.close();
				break;
			}
		}
	}
	public void windowClosed(WindowEvent e){}
	public void windowOpened(WindowEvent e){ }
	public void windowClosing(WindowEvent e){ 
		socket.close(); 
		this.thread = null; 
		this.dispose();
	}
	public void windowIconified(WindowEvent e){ }
	public void windowDeiconified(WindowEvent e){ }
	public void windowActivated(WindowEvent e){ }
	public void windowDeactivated(WindowEvent e){ }
}


[戻る]

33 ---TCPクライアントフレームプログラム

/*
    
    
   */
//   TCP利用のクライアント実験 インターネットブラウザもどきを作成する。
/* jarファイル作成コマンド
%JAVA_HOME%\bin\jar cmvf frame33.txt frame33.jar frame33.class

frame33.txtの内容
Main-Class: frame32
Class-Path: .
*/
import java.awt.*; 		//TextFieldなど利用のため
import java.awt.event.*;	//ActionListenerなど利用のため
import java.net.*;		//InetAddress利用のため
import java.lang.*;		//Exception利用のため
import java.io.*;		//streamのバッファリングなど

public class frame33 extends Frame implements ActionListener, Runnable,WindowListener{
	Button btn;		//送信ボタン用
	TextArea msg;		//メッセージ表示用
	TextField txtRecPort;	//受信ポート
	TextField txtSndIp; 	//送信先IP用
	TextField txtSndPort; 	//送信先port用
	TextField txtSndMsg; 	//送信先port用
	Thread thread;		//受信ループスレッド
	Socket socket;		//ソケット
	BufferedReader reader;	//受信スレットで受信

	
	byte crlf [] = {13,10};//キャリッジリターン(CR),改行(LF)の並び で、送信時の区切り用
			//上記を"\r\n" として、この文字列からgetBytes()でバイト列へ変換する手法もあるが、JavaはOSにより変換憶が異なるので上手く行かない場合があるようだ(実験より)

	public frame33(){
		init( null );
		setSize(640,300);
		pack();
		show();
	}
	
	public frame33(Socket parmSock){//サーバーで利用の予定
		init( parmSock );
		setSize(640,300);
		pack();
		show();
	}

	public static void main(String argv[]){
		frame33 frm = new frame33();
	}
	
	public void init(Socket parmSock){//applet版に変更時も利用できるように・・
		setLayout(new BorderLayout());
		//各種メッセージ表示用
		add(msg = new TextArea(5,60),BorderLayout.CENTER);
		
		Panel panel;
		add(panel = new Panel(),BorderLayout.SOUTH); //下に配置のパネル
		panel.add(new Label("ip"));
		panel.add(txtSndIp = new TextField());
		panel.add(new Label("port"));
		panel.add(txtSndPort = new TextField());
		panel.add(new Label("msg"));
		panel.add(txtSndMsg = new TextField(50));
		panel.add(btn = new Button("接続"));
		btn.addActionListener(this);//ボタン操作オブジェクト登録

		if(parmSock == null){ 
			//下位パネル配置の内容設定
			txtSndIp.setText("yuu7777.fc2web.com");
			txtSndPort.setText("80");
			txtSndMsg.setText("GET http://yuu7777.fc2web.com/applet/javatext.html HTTP/1.1");

			//上位パネル配置
			add(panel = new Panel(),BorderLayout.NORTH);
			try {
				InetAddress local = InetAddress.getLocalHost(); 
				panel.add(new Label("IP[" + local.getHostAddress() + "]"));
				panel.add(new Label(" Host Name[" + local.getHostName() + "]"));
			} 
			catch (UnknownHostException e){
				msg.append(e.toString());
			}
		} else {
			socket = parmSock;
			InetAddress iadr = socket.getInetAddress();//接続先アドレス
			txtSndIp.setText(iadr.getHostAddress());
			txtSndPort.setText("" + socket.getPort());
			thread = new Thread(this);
			thread.start();	//受信スレッドスタート		
			btn.setLabel("送信");
		}
		this.addWindowListener(this);//ウインドウ操作オブジェクト登録
	}
	
	public void send(OutputStream os, String sndMsg) throws IOException { //送信メソッド
		msg.append("送信文字列【" + sndMsg + "】\n");
		os.write(sndMsg.getBytes());
		os.write(crlf);
	}
	
	public void actionPerformed(ActionEvent e){ //接続・送信兼用ボタン処理
		try {
			if(socket == null) {//接続
				InetAddress sendIp = InetAddress.getByName(txtSndIp.getText());
				//InetAddress sendIp = InetAddress.getByName("proxy.scc01");プロキシがある場合
				int port = Integer.parseInt(txtSndPort.getText());
				socket = new Socket( sendIp ,  port);
				btn.setLabel("送信");
				msg.append("【connect】\n");
				if(thread == null){// 受信スレッドが動いていない?
					thread = new Thread(this);
					thread.start();	//受信スレッドスタート
				}
			} else {//送信
				String sndMsg;//送信文字列管理用
				OutputStream os = socket.getOutputStream();
				sndMsg = new String(txtSndMsg.getText());
				send(os,sndMsg);//送信
				sndMsg = new String("HOST: " + txtSndIp.getText());//HOSTの設定
				send(os,sndMsg);
				os.write(crlf); // 区切りのため一回多く送る。
			}
		} catch(Exception es){
			msg.append("【connect:" + es.toString() + "\n】");
			try {
				socket.close();
			}
			catch(Exception ec){
				msg.append("【close:" + es.toString() + "\n】");
			}
			socket = null;
			btn.setLabel("接続");
		}
	}
	
	public void run(){//受信処理のスレッド
	        String str;
		try {
			reader = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
			while((str = reader.readLine())!= null){
				msg.append(str + "\n");
			}
			msg.append("【close】\n");
			socket.close();//ソケットクローズ
		}
		catch(Exception e){
			msg.append("【run:" + e.toString() + "】\n");
		}
		socket = null;
		thread = null;
		btn.setLabel("接続");
	}
	public void windowClosed(WindowEvent e){}
	public void windowOpened(WindowEvent e){ }
	public void windowClosing(WindowEvent e){ 
		try {socket.close();} catch(Exception es){}
		this.dispose();
	}//閉じるボタン処理
	public void windowIconified(WindowEvent e){ }
	public void windowDeiconified(WindowEvent e){ }
	public void windowActivated(WindowEvent e){ }
	public void windowDeactivated(WindowEvent e){ }
}



[戻る]

34 ---TCPサーバーフレームプログラム

/*
    
    
   */
//   TCP利用のサーバー 
/* jarファイル作成コマンド
%JAVA_HOME%\bin\jar cmvf frame34.txt frame34.jar frame34.class frame33.class

manifestファイルの内容
Main-Class: frame34
Class-Path: .
*/
//前述のframe33.classクラスを利用
import java.awt.*;	//TextFieldなど利用のため
import java.awt.event.*;//ActionListenerなど利用のため
import java.net.*;	//InetAddress利用のため
import java.lang.*;	//Exception利用のため
import java.io.*;

public class frame34 extends Frame implements ActionListener ,Runnable, WindowListener{
	ServerSocket server_socket; 	//サーバーのソケット
	Choice choIp;	//選択メニュー管理 受け付け用IP
	TextField txtRecPort;		//受信ポート
	Button btn;			//Listenボタン用
	TextArea msg;			//メッセージ表示用
	Thread thread;
	public frame34(){
		super("TCP ソケットサーバーの動作確認");
		add( choIp = new Choice(),BorderLayout.NORTH); //上に配置のパネル
		add( txtRecPort = new TextField("5000"),BorderLayout.CENTER); //上に配置のパネル
		add( btn = new Button("Listen"),BorderLayout.EAST); //上に配置のパネル
		add( msg = new TextArea("",10,50),BorderLayout.SOUTH); //上に配置のパネル
		try {
			InetAddress localhost = InetAddress.getLocalHost();
			String	nameHost = localhost.getHostName();
			InetAddress inets[] = InetAddress.getAllByName(nameHost);
			for(int i = 0; i < inets.length; i++){	
				String item = inets[i].getHostAddress();//IPアドレスの列挙
				choIp.add(item);
			}
		} catch(Exception e){ msg.append(e.toString() + "\n"); }
		setSize(300,150);
		pack();
		show();
		this.addWindowListener(this);
		btn.addActionListener(this);
	}
	public static void main(String argv[]){
		frame34 frm = new frame34();
	}
	public void actionPerformed(java.awt.event.ActionEvent ea){//Listen button処理
		try {
			thread = new Thread(this);
			thread.start();	//受信スレッドスタート
			btn.setEnabled(false);
		}
		catch(Exception e){msg.append(e.toString() + "\n"); }
	}
	public void run(){//受け付けのスレッド
		try {
			int port = Integer.parseInt(txtRecPort.getText());
			server_socket = new ServerSocket(port);	//サーバーソケット生成
			for(;;){
				Socket socket = server_socket.accept(); //接続受け入れ
				new frame33(socket);
			}
		}catch(Exception e){msg.append(e.toString() + "\n"); }
	}
	public void windowClosed(WindowEvent e){}
	public void windowOpened(WindowEvent e){ }
	public void windowClosing(WindowEvent e){
		try {server_socket.close(); } catch (Exception es){}
		this.dispose();
	}//閉じるボタン処理
	public void windowIconified(WindowEvent e){ }
	public void windowDeiconified(WindowEvent e){ }
	public void windowActivated(WindowEvent e){ }
	public void windowDeactivated(WindowEvent e){ }

}



[戻る]

---

---
SEO [PR] 爆速!無料ブログ 無料ホームページ開設 無料ライブ放送