• 締切済み

ソケットにおけるメッセージの送受信について

matsu5200の回答

回答No.3

askaaskaさんのおっしゃっている通り、基本的な理解が足りないんじゃないですかね。 まず、1~4について主語を付けて整理したらどうでしょう? ----------------------------------------------------- 1)クラスA:ソケット通信でメッセージ送信 2)クラスB:ソケット通信によるメッセージを取得(⇒受信) 3)クラスB:ソケット通信で返信する 4)クラスA:ソケットによるメッセージを再取得する ----------------------------------------------------- 登場人物 : ・クライアントソケット・・・socket = new Socket("localhost", 5555); ・サーバソケット・・・Socket socket = serverSocket.accept(); 動作 : ・書き込む(out) ・読み込む(in) でどうでしょうか。

kannitiha
質問者

お礼

お礼遅くなりました。 かなり、実力不足でした。 いまだに少し理解しきれていませんが、一度試して 再度もう少し勉強しなおしてまた質問させてもらいます。 回答ありがとうございました。 また、よろしくお願いします。

関連するQ&A

  • 初歩的なソケット通信(java)

    初歩的なソケット通信(java) javaのソケット通信プログラムについて質問させて頂きます。まだまだ基礎の段階なのですが、詰まってしまたので、良かったら教えてください。 以下プログラムコード ------------------------------------- //サーバー側 import java.net.*; import java.io.*; public class Server { static int port = 12345; public static void main(String[] args) { try{ //サーバソケットの作成 ServerSocket ssoc = new ServerSocket(port); //メインループ while(true){ try{ System.out.println("クライアントからの接続を"+ port +"で待ちます"); Socket soc = ssoc.accept(); System.out.println(soc.getInetAddress().getHostName()+"から接続を受けました"); //処理をスレッドに任せます new Connect(soc); }catch(IOException e1){ e1.printStackTrace(); } } }catch(IOException e2){ e2.printStackTrace(); } } } class Connect extends Thread{ private Socket socket = null; public Connect(Socket socket){ this.socket = socket; //スレッド開始 this.start(); } public void run(){ try{ //出力ストリームを取得 OutputStream os = socket.getOutputStream(); PrintWriter out = new PrintWriter(os,true); //入力ストリームを取得 InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader in = new BufferedReader(isr); String inputLine; while((inputLine = in.readLine()) != null){ //System.out.println(inputLine); out.println(inputLine); } System.out.println("処理が終わったので接続を切ります"); in.close(); out.close(); socket.close(); }catch(Exception e1){ try{ socket.close(); }catch(Exception e2){ e2.printStackTrace(); } } } }

  • JavaのTCPソケット通信プログラムについて

    初めてJavaでTCPソケット通信を書いてみたのですが、質問です。ソケット通信をサーバーとクライアント側で確立した後、メッセージの送受信をやるとても簡素なプログラムを作成しました。一回目の送受信をするだけだと上手くいくのですが、同じコネクション内で二回目の送受信をするよう追記したところ動作がおかしくなりました。(一つ目のメッセージも受信しないまま画面が停止した状態になる)何が問題なのでしょうか。 (Receiver.java) public class Receiver { public static final int PORT = 30000; public static void main(String[] args) { try { ServerSocket serverSoc = new ServerSocket(PORT); Socket socket = null; System.out.println("Waiting for Connection.."); socket = serverSoc.accept(); System.out.println("Connection from "+socket.getInetAddress()); // receive message BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("Message from sender ="+new String(br.readLine())); //send message←ここを追記するとおかしくなりました。 String message = "Hey This is receiver"; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); System.out.println("I will send: "+message); bw.write(message); br.close(); bw.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } (Sender.java) public class Sender { public static final int PORT = 30000; public static void main(String[] args) { try { InetAddress LocalHost = InetAddress.getLocalHost(); InetSocketAddress socketAddress = new InetSocketAddress(LocalHost, PORT); Socket socket = new Socket(); socket.connect(socketAddress, 10000); //send message String message = "Hey This is sender"; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); System.out.println("I will send: "+message); bw.write(message); // receive message←同じくここを追記するとおかしくなりました。 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("Message from receiver ="+new String(br.readLine())); br.close(); bw.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }

  • この各行のプログラムの意味を教えてください!

    各行のプログラムがなにをしてるかちょっとわからないので誰か教えてください><お願いします! PrintWriter out=new PrintWriter(socket.getOutStream(),true); out.println("hello,World!"); BufferedReader in=new BufferedReader( new InputStreamReader(socket.getInputStream()); String result=in.readLine();

    • ベストアンサー
    • Java
  • HttpのResponseが文字化け

    以下のプログラムの結果が文字化けします。 正しい文字コード(EUC-JP)にしているのですが 文字化けしてしまいます。 解消方法を教えて下さい。 ----- import java.net.*; import java.io.*; public class HelloWorldSocketClient { public static void main(String[] args) throws Throwable{ Socket socket = new Socket("www.sumishinam.co.jp", 80); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.println("GET / HTTP1.0\n"); String buff; while((buff=in.readLine())!=null){ System.out.println(new String(buff.getBytes(),"EUC-JP")); } out.close(); in.close(); socket.close(); } }

  • Socketの使用方法について

    Socketの使用方法について サーバ側クラスA クライアント側クラスB とあり、Aは常駐しておりBから接続が合った場合に処理を行い、 処理後には待機状態に再び戻ります。 上記の場合に Aのクラスは以下のように作成しましたが、★の部分でCloseではなく、このままこのソケットを使用して待機したいです。 (ほぼ同時刻に複数のアクセスがあるため、資源の事を考えて使いまわしたいです。) どのような手段があるのかご指導お願い致します。 又、そもそもソケットに関しての理解が足りないとも思いますので、参考サイトを教えていただけると幸いです。 クラスA ServerSocket svsock = new ServerSocket(port); while (true) { Socket socket = svsock.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedWriter out = new BufferedWriter(new PrintWriter(socket.getOutputStream(), true)); // 処理結果を受信 String line; if ((line = in.readLine()) != null) { System.out.println("受け取ったメッセージ : " + line); out.write("サーバで表示。"); out.newLine(); out.flush(); } socket.close(); // ★ }

    • ベストアンサー
    • Java
  • echoサーバについて

    javaを勉強しています。 echoサーバをつかったサンプルがあり、vinelinux上でコンパイリし実行したのですが、ioexceptionの例外が出ているようです。 echoサーバは動いていないのでしょうか?? echoサーバが動いているかどうか確認する方法はないですか? このようなプログラムです。 import java.io.*; import java.net.*; public class EchoClient{ public static void main(String args[])throws IOException{ Socket echoS = null; BufferedReader in = null; PrintStream out = null; try{ echoS = new Socket("1300",7); in = new BufferedReader(new InputStreamReader(echoS.getInputStream())); out = new PrintStream(echoS.getOutputStream()); }catch(UnknownHostException e){ System.out.println("ホストに接続できません"); System.exit(1); }catch(IOException e){ System.out.println("ioコネクションを得られません"); System.exit(1); } BufferedReader stdln = new BufferedReader(new InputStreamReader(System.in)); String typedString; while((typedString = stdln.readLine()) != null){ out.println(typedString); System.out.println("サーバーからのエコー" + in.readLine()); } in.close(); out.close(); stdln.close(); echoS.close(); } }

    • ベストアンサー
    • Java
  • 文字化けします。

    お世話になります。 ソケットでサーバとクライアントを接続しています。 コーディングの概略は次の通りです。 【クライアント】 PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"EUC_JP")); out.println("かきくけこ"); System.out.println(in.readLine()); 【サーバ】 PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"Shift_JIS")); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); out.println(inputLine); //←これはクライアントでも文字化けしない。 String s1 = "あいうえお"; String u1 = new String(s1.getBytes("xxxxx"), "yyyyy"); out.println(u1); //←文字化けする。 } お伺いしたいのは文字コード変換についてです。 サーバ:RedhatLinux クライアント:Windowsでして、 サーバ側コーディングの String s1 = "あいうえお"; としている文字列を クライアント側の // 読み込んだデータを表示 System.out.println(in.readLine()); で表示したいのですが、文字が化けて(????←このようになります)困っています。 文字コード変換しなければいけないと思うのですが、 getBytesを使うのでしょうか? もしgetBytesを使うならどのように書けばいいのかがわかりません。 分かりにくい説明で申し訳ありませんが、 ご教授ください。宜しくお願いします。

    • ベストアンサー
    • Java
  • 今勉強中のjavaで。わからないことがあります。

    import java.io.*; class Ireru { public static void main(String args[]) throws IOException{ System.out.println("あなたは何歳ですか?"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str1 = br.readLine(); int num =Integer.parseInt(str1); System.out.println("あなたは" + num +"歳です。"); } } ------------------------------- import java.io.*; class Ireru { public static void main(String args[]) throws IOException{ System.out.println("あなたは何歳ですか?"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str1 = br.readLine(); System.out.println("あなたは" + str1 +"歳です。"); } } なぜ下では悪いのですか?なぜnum をつかないといけないかがわかりません。正確には str1とnumの違いがわからなくて困っています。何が混乱の原因ですか?

    • ベストアンサー
    • Java
  • TCP関係のjavaプログラム

    TCPでオウム返しをするサーバとクライアントソフトでクライアント側でピリオドだけを入力すると接続を切るプログラムを作っているのですがなかなか思い通りにいきません。 正しいソースコードを教えてください。 クライアント側のソースコード import java.io.*; import java.net.*;   public class echoClient { public static void main(String[] args) { Socket echoSocket = null; DataOutputStream os = null; BufferedReader is = null;   try { echoSocket = new Socket("localhost", 9999); os = new DataOutputStream(echoSocket.getOutputStream()); is = new BufferedReader(new InputStreamReader(echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: localhost"); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: localhost"); }   if (echoSocket != null && os != null && is != null) { try { os.writeBytes("HELLO\n");   String responseLine; if ((responseLine = is.readLine()) != null) { System.out.println("Server: " + responseLine); }   os.close(); is.close(); echoSocket.close(); } catch (UnknownHostException e) { System.err.println("Trying to connect to unknown host: " + e); } catch (IOException e) { System.err.println("IOException: " + e); } } } } サーバー側のプログラム import java.io.*; import java.net.*; public class echoServer { public static void main(String args[]) { ServerSocket echoServer = null; String line; BufferedReader is; PrintStream os; Socket clientSocket = null; try { echoServer = new ServerSocket(9999); } catch (IOException e) { System.out.println(e); } try { clientSocket = echoServer.accept(); is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); os = new PrintStream(clientSocket.getOutputStream()); while (true) { line = is.readLine(); os.println(line); } } catch (IOException e) { System.out.println(e); } }

  • 下のように URLConnections クラスと sockets ク

    下のように URLConnections クラスと sockets クラスでは使用してるプロトコルが違うのか googleからの反応が異なります URLConnections クラスは反応を示さず sockets クラスは読み込めます そこで、URLConnectionsクラスとsocketsクラスが使用している TCP/IP階層図では URLConnectionsクラスとsocketsクラスはどの階層に該当するのでしょうか? import java.io.*; import java.net.*; import java.util.Date; class URLConnections { public URLConnections() { try{ int character; URL url = new URL( "http://www.google.co.jp" ); URLConnection urlconnection = url.openConnection(); int contentlength = urlconnection.getContentLength(); if( contentlength > 0 ) { InputStream in = urlconnection.getInputStream(); while( (character = in.read() ) != -1 ) { System.out.print( (char)character ); } } }catch(Exception e) { System.out.println( "URLConnections で例外発生"); } } } class sockets { public sockets() { try { System.out.println( "socket start" ); Socket s = new Socket( "www.google.co.jp", 80 ); BufferedReader in = new BufferedReader( new InputStreamReader( s.getInputStream() ) ); PrintWriter out = new PrintWriter( s.getOutputStream() ); out.print( "GET /index.html\n\n" ); out.flush(); String line; while( (line=in.readLine())!= null ){ System.out.println( line ); } System.out.println( "socket end" ); }catch(Exception e) { } } } public class app { public static void main( String[] args) { URLConnections u = new URLConnections(); System.out.println( "end1\n" ); sockets s = new sockets(); System.out.println( "end2\n" ); } }

    • ベストアンサー
    • Java