0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaでSLMP通信(ソケット通信,TCP通信)(ASCII,Binary)

Last updated at Posted at 2020-09-04

#ASCII

####Server

ASCII-Server

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerASCII {

        //80番ポートを使用
		private static final int LISTEN_PORT = 80;
		public static void main(String[] args){

			//受け入れソケット
			Socket socket =null;

			//受動的ソケット(サーバーソケット)
			ServerSocket ss_socket = null;
			try {
				ss_socket = new ServerSocket(LISTEN_PORT);
			    } catch (IOException e1) {
				// TODO 自動生成された catch ブロック
				e1.printStackTrace();
			    }

			//サーバー側の処理を書く
			try{

				System.out.println("クライアント待ち");

				socket = ss_socket.accept();

				//入出力のリーダー、ライター
				BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

				while (true) {
				char[] buf = new char[1024];
				if(in.read(buf) != -1){
					try{
						System.out.println("receive↓↓");
						System.out.print(buf);
						Thread.sleep(250);
		            }
		            catch(Exception ex){
		                ex.printStackTrace();
		            }
				}
				System.out.print("\n");

				if (buf.equals("bye")) {
	                break;
	        	}

				out.write(buf);
				out.flush();
				}

			}catch(IOException err){
				err.printStackTrace();
			}finally{
				try{
					if (socket!=null){
						socket.close();
					}
					if (ss_socket!=null){
						ss_socket.close();
					}
					System.out.println("サーバー側終了です");

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
	    }
 }

####Client

ASCII-Client

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientASCII {

	private static final String HOST = "localhost";//接続先
	private static final int PORT = 80;//80番ポートを使用
	private static final String err = "0000";

	public static void main(String[] args) throws InterruptedException {
		ClientASCII aa = new ClientASCII();
		aa.Cascii();

	}

	public void Cascii() throws InterruptedException{
		Socket socket = null;
		try {
			socket = new Socket(HOST,PORT);
		} catch (UnknownHostException e1) {
			// TODO 自動生成された catch ブロック
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO 自動生成された catch ブロック
			e1.printStackTrace();
		}
		try{
			//受信、送信のリーダーとライター
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			BufferedReader csInput = new BufferedReader (new InputStreamReader(System.in));

			while (true) {
			System.out.println("-------------------");
			System.out.println("コマンドを入力して下さい");
			System.out.println("-------------------");

			//サーバーに送るメッセージ
			String sendMSG = csInput.readLine();
			String sub;
			String check;

			if(sendMSG.isEmpty()) {
        		System.out.println("↓↓なんかしらいれな↓↓");
        		continue;
        	}

			out.write(sendMSG);
			out.flush();
			//byeの入力でループを抜ける
			if (sendMSG.equals("bye")) {
				break;
			}

			//サーバから文字列を受信
			System.out.print("receive->");
			char[] buf = new char[1024];
			if(in.read(buf) != -1){
				System.out.print(buf);
				System.out.println("\n");
	    		sub = new String(buf);

				if(!check.equals(err)) {
					System.out.println("エラー発生");
				}
			} else {
				System.out.println("returnがnullです");
				break;
			}
			}

		}catch(IOException err){
			err.printStackTrace();
		}finally{
			try {
				if (socket != null) {
					socket.close();
				}
		        System.out.println("クライアント側終了です");

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

#Binary

####Server

Binary-Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.codec.binary.Hex;

public class ServerBinary {

	public static void main(String[] args) {

		ServerBinary s1 = new ServerBinary();
		s1.runSample();

	}

	void runSample() {

		ServerSocket sSocket = null;
		Socket socket = null;
		BufferedReader reader = null;
		PrintWriter writer = null;
		OutputStream os = null;
		byte crlf [] = {13,10};

		try{
			//IPアドレスとポート番号を指定してサーバー側のソケットを作成
			sSocket = new ServerSocket();
			sSocket.bind(new InetSocketAddress
					("localhost",8000));

			System.out.println("クライアントからの入力待ち状態");

			//クライアントからの要求を待ち続けます
			socket = sSocket.accept();

			//クライアントからの受取用
			reader = new BufferedReader(
					new InputStreamReader
					(socket.getInputStream()));

			os = socket.getOutputStream();

			//無限ループ byeの入力でループを抜ける
			String line = null;
	        while (true) {

	        	line = reader.readLine();
	        	byte[] sbyte = line.getBytes();
	        	String ddd = new String(Hex.encodeHex(sbyte));

	        	if (line.equals("bye")) {
	                break;
	        	}
		        os.write(sbyte);
		        os.write(crlf);

	            System.out.println("クライアントで入力された文字=" + ddd);
	        }
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if (reader!=null){
					reader.close();
				}
				if (socket!=null){
					socket.close();
				}
				if (sSocket!=null){
					sSocket.close();
				}
	            System.out.println("サーバー側終了です");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

####Client

Binary-Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import org.apache.commons.codec.binary.Hex;

public class ClientBinary {

	public static void main(String[] args) {

		ClientBinary s2 = new ClientBinary();
		s2.runSample();
	}

	void runSample() {

		Socket cSocket = null;
		BufferedReader csInput = null;
		PrintWriter writer = null;
		BufferedReader reader = null;

		try{
			//IPアドレスとポート番号を指定してクライアント側のソケットを作成
			cSocket = new Socket("localhost", 8000);

			//クライアント側での入力用
			csInput = new BufferedReader
					(new InputStreamReader(System.in));

			//クライアント側からサーバへの送信用
			writer = new PrintWriter
					(cSocket.getOutputStream(), true);

			//サーバ側からの受取用
			reader = new BufferedReader
					(new InputStreamReader
							(cSocket.getInputStream()));

			//無限ループ byeの入力でループを抜ける
			String line = null;
			String read = null;
			while (true) {
				System.out.println("-------------------");
				System.out.println("コマンドを入力して下さい");
				System.out.println("-------------------");

	        	line = csInput.readLine();
	        	byte[] bi = line.getBytes();

				//送信用の文字を送信
	        	if(line.isEmpty()) {
	        		System.out.println("↓↓なんかしらいれな↓↓");
	        		continue;
	        	}

	        	writer.println(bi);
				//byeの入力でループを抜ける
				if (line.equals("bye")) {
					break;
				}

				read = reader.readLine();
				byte[] sbyte = read.getBytes();
				String ddd = new String(Hex.encodeHex(sbyte));
				System.out.println("return: " + ddd);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if (reader != null) {
					reader.close();
				}
				if (writer != null) {
					writer.close();
				}
				if (csInput != null) {
					csInput.close();
				}
				if (cSocket != null) {
					cSocket.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
	        System.out.println("クライアント側終了です");
		}
	}
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?