この記事では、Socketに基づいてJavaによって実装されたクライアントとサーバーの通信機能について説明します。次のように、参照のために共有してください。
次のコードは、MAソルジャーのチャットプロジェクトを指します。最初にchatserver.javaを実行してポートリスニングを実装し、chatclient.javaを実行します。
クライアントインスタンス
chatclient.java
パッケージsocketdemo; import java.awt。*; import java.awt.event。*; import java.io。*; import java.net。 dataoutputStream dos = null; datainputStream dis = null; private boolean bconnected = false; textfield tftxt = new TextField(); textarea tacontent = new Textarea();スレッドtrecv = newスレッド(new recvthread()); public static void main(string [] args){new chatclient()。launchframe(); } public void launchframe(){setLocation(400、300); this.setsize(300、300); add(tftxt、borderlayout.south); add(tacontent、borderlayout.north);パック(); this.addwindowlistener(new WindowAdapter(){@Override public void windowclosing(windowevent arg0){disconnect(); system.exit(0);}}); tftxt.addactionlistener(new Tflistener()); setVisible(true);接続する(); trecv.start(); } public void connect(){try {s = new Socket( "localhost"、8888); dos = new DataOutputStream(s.getOutputStream()); dis = new DatainputStream(s.getInputStream()); System.out.println( "Connected!"); bconnected = true; } catch(unknownhostexception e){e.printstacktrace(); } catch(ioexception e){e.printstacktrace(); }} public void disconnect(){try {dos.close();開示する(); s.close(); } catch(ioexception e){e.printstacktrace(); } / * * try {bconnected = false; trecv.join(); } catch(arturnedexception * e){e.printstacktrace(); }最後に{try {dos.close();開示する(); * s.close(); } catch(ioexception e){e.printstacktrace(); }} */} private class tflistenerはactionlistener {public void actionperformed(actionevent e){string str = tftxt.getText()。trim(); // tacontent.settext(str); tftxt.settext( ""); try {// System.out.println(s); dos.writeutf(str); dos.flush(); // dos.close(); } catch(ioexception e1){e1.printstacktrace(); }}} private class recvthreadはrunnable {public void run(){try {while(bconnected){string str = dis.readutf(); // system.out.println(str); tacontent.settext(tacontent.getText() + str + '/n'); }} catch(socketexception e){system.out.println( "exit、bye!"); } catch(eofexception e){system.out.println( "例外、bye -bye!"); } catch(ioexception e){e.printstacktrace(); }}}}ソケットサーバーコード
chatserver.java
パッケージsocketdemo; import java.io。*; import java.net。*; Import java.util。 SSS = null; list <client> clients = new ArrayList <Client>(); public static void main(string [] args){new Chatserver()。start(); } public void start(){try {ss = new Serversocket(8888); start = true; } catch(bindexception e){system.out.println( "Port in inout ......"); System.out.println(「関連するプログラムを閉じてサーバーを再実行してください!」); System.Exit(0); } catch(ioexception e){e.printstacktrace(); } try {while(start){socket s = ss.accept();クライアントc = new Client(s); system.out.println( "Client Connected!");新しいスレッド(c).start(); clients.add(c); // 開示する(); }} catch(ioexception e){e.printstacktrace(); }最後に{try {ss.close(); } catch(ioException e){// todo auto-fenated catch block e.printstacktrace(); }}} classクライアントはrunnable {private socket s;プライベートDatainputStream dis = null; private dataoutputStream dos = null; private boolean bconnected = false; public client(socket s){this.s = s; try {dis = new DatainputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); bconnected = true; } catch(ioexception e){e.printstacktrace(); }} public void send(string str){try {dos.writeutf(str); } catch(ioException e){clients.remove(this); system.out.println( "他のパーティが終了しました!リストから削除しました!"); // e.printstacktrace(); }} public void run(){try {while(bconnected){string str = dis.readutf(); System.out.println(str); for(int i = 0; i <clients.size(); i ++){client c = client.get(i); c.send(str); // system.out.println( "文字列send!"); } / * * for(iterator <client> it = client.iterator(); * it.hasnext();){client c = it.next(); c.send(str); } * / / * * iterator <client> it = client.iterator(); * while(it.hasnext()){client c = it.next(); c.send(str); *} */}} catch(eofexception e){system.out.println( "クライアントクローズ!"); } catch(ioexception e){e.printstacktrace(); }最後に{try {if(dis!= null)dis.close(); if(dos!= null)dos.close(); if(s!= null){s.close(); // s = null; }} catch(ioexception e1){e1.printstacktrace(); }}}}}}ローカルテスト実行の結果:
クライアントウィンドウを閉じた後、プロンプトメッセージは次のとおりです。
Java関連のコンテンツの詳細については、このサイトのトピックをご覧ください:「Javaソケットプログラミングスキルの概要」、「Javaファイルとディレクトリの操作スキルの概要」、「Javaデータ構造とアルゴリズムに関するチュートリアル」、「Java Operation Dom Nodeスキルの概要」、Java Cache操作スキルの概要」
この記事がみんなのJavaプログラミングに役立つことを願っています。