Socketサンプル


※上記の広告は60日以上更新のないWIKIに表示されています。更新することで広告が下部へ移動します。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;

public class ClientServerSocketSample {
	private final static int port = 50000;

	static class SimpleServerSession implements Runnable {

		private Socket socket;

		public SimpleServerSession(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {

			try {
				BufferedInputStream input = new BufferedInputStream(socket
						.getInputStream());
				BufferedOutputStream output = new BufferedOutputStream(socket
						.getOutputStream());

				while (true) {
					// インプットストリームからバイトを取得
					byte[] readByte = new byte[1024];
					int streamSize = -1;
					RecievedData data = new RecievedData();
					while ((streamSize = input.read(readByte)) != -1) {
						ByteBuffer re = ByteBuffer.wrap(new byte[streamSize]);
						re.put(readByte, 0, streamSize);
						data.putByte(re.array());
						if (data.isCompleted()) {
							break;
						}
					}

					ByteBuffer bytebuf = ByteBuffer.wrap(new byte[data
							.getSize()]);
					bytebuf.putInt(data.getDataSize());
					bytebuf.put(data.getData().array());
					output.write(bytebuf.array());
					output.flush();
				}
			} catch (Exception e) {
				if (socket != null) {
					try {
						socket.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		}
	}

	public static void main(String[] args) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					ServerSocket server = new ServerSocket(port);
					while (true) {
						Socket soket = server.accept();
						new Thread(new SimpleServerSession(soket)).start();
						System.out.println("accept soket:" + soket);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				System.out.println("end");
			}
		}).start();

		Socket socket = new Socket();
		try {
			socket.connect(new InetSocketAddress(port));

			BufferedOutputStream out = new BufferedOutputStream(socket
					.getOutputStream());
			BufferedInputStream input = new BufferedInputStream(socket
					.getInputStream());
			for (int i = 0; i < 10000; i++) {

				// 送信
				String sendString = "sample 日本語";
				byte[] senddata = sendString.getBytes();
				ByteBuffer bufData = ByteBuffer.allocate(4 + senddata.length);
				bufData.putInt(senddata.length);
				bufData.put(senddata);
				out.write(bufData.array());
				out.flush();

				// 受信
				// インプットストリームからバイトを取得
				byte[] readByte = new byte[1024];
				int streamSize = -1;
				RecievedData data = new RecievedData();
				while ((streamSize = input.read(readByte)) != -1) {
					ByteBuffer re = ByteBuffer.wrap(new byte[streamSize]);
					re.put(readByte, 0, streamSize);
					data.putByte(re.array());
					if (data.isCompleted()) {
						break;
					}
				}
				String recieve = new String(data.getData().array());
				if (recieve.equals(sendString)) {

				} else {
					System.err.println("errror");
				}
			}
			System.out.println("終了");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

class RecievedData {
	private RecievedState state;
	private RecievedState sizeData;
	private RecievedState messageData;
	private boolean completed;

	public RecievedData() {
		sizeData = new RecievedState(this, 4);
		state = sizeData;
	}

	public void putByte(byte[] data) {
		state.putByte(data);
	}

	void full(RecievedState recievedState, ByteBuffer fullData,
			ByteBuffer restData) {
		if (recievedState == sizeData) {
			fullData.position(0);
			messageData = new RecievedState(this, fullData.getInt());
			state = messageData;
			if (restData != null) {
				putByte(restData.array());
			}
		} else if (recievedState == messageData) {
			if (restData != null) {
				throw new RuntimeException("データサイズが不一致です");
			}
			completed = true;
		}
	}

	public ByteBuffer getData() {
		if (messageData != null) {
			return messageData.getData();
		}
		return null;
	}

	public boolean isCompleted() {
		return completed;
	}

	public int getSize() {
		if (messageData != null) {
			return sizeData.getSize() + messageData.getSize();
		}
		return sizeData.getSize();
	}

	public int getDataSize() {
		if (messageData != null) {
			return messageData.getSize();
		}
		return sizeData.getSize();
	}

	private class RecievedState {

		private int size;

		public int getSize() {
			return size;
		}

		private RecievedData recievedData;

		private ByteBuffer buf;

		private boolean full;

		public RecievedState(RecievedData recievedData, int size) {
			this.size = size;
			buf = ByteBuffer.wrap(new byte[size]);
			this.recievedData = recievedData;
		}

		public void putByte(byte[] data) {
			if (full) {
				throw new RuntimeException("これ以上書きこむことはできません");
			}
			int rest = size - buf.position();
			if (rest == data.length) {
				buf.put(data, 0, data.length);
				recievedData.full(this, buf, null);
				full = true;
			} else if (rest > data.length) {
				buf.put(data, 0, data.length);
			} else {
				buf.put(data, 0, rest);
				ByteBuffer restBuf = ByteBuffer.wrap(new byte[data.length
						- rest]);
				restBuf.put(data, rest, data.length - rest);
				recievedData.full(this, buf, restBuf);

				full = true;
			}
		}

		public ByteBuffer getData() {
			return buf;
		}
	}
}
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。