Javaでソケット通信

ソケット通信するサンプル作ってみた。

サーバ


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class WordManageServer {

private static final int PORT = 8888;

public static void main(String[] args) {

ServerSocket serverSocket = null;
Socket socket = null;

try {

// サーバーソケットの生成
serverSocket = new ServerSocket(PORT);

for (;;) {

System.out.println("wait request.");
socket = serverSocket.accept();
System.out.println("accept [" + socket.getInetAddress() + "]");

// スレッド起動
new WordManagerThread(socket);
}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

serverSocket.close();

} catch (IOException e) {

e.printStackTrace();
}
}
}
}

class WordManagerThread extends Thread {

private Socket socket = null;

public WordManagerThread(Socket socket) {

this.socket = socket;
this.start();
}

public void run() {

PrintWriter out = null;
BufferedReader in = null;

try {

// 出力ストリームを取得
out = new PrintWriter(socket.getOutputStream(), true);

InputStream inputStream = socket.getInputStream();
byte[] func = new byte[4];
byte[] dt = new byte[4];

inputStream.read(func);
int val1 = ((func[3] & 0xff) << 24) | ((func[2] & 0xff) << 16)
| ((func[1] & 0xff) << 8) | (func[0] & 0xff);

inputStream.read(dt);
int val2 = ((dt[3] & 0xff) << 24) | ((dt[2] & 0xff) << 16)
| ((dt[1] & 0xff) << 8) | (dt[0] & 0xff);

System.out.println(val1);
System.out.println(val2);

} catch (IOException e) {

e.printStackTrace();

} finally {

close(socket, out, in);
}
}

/**
* @param socket
* @param out
* @param in
*/
private static void close(Socket socket, PrintWriter out, BufferedReader in) {

if (out != null) {

out.close();
}

if (in != null) {

try {

in.close();

} catch (IOException e) {

e.printStackTrace();
}
}

if (socket != null) {

try {

socket.close();

} catch (IOException e) {

e.printStackTrace();
}
}
}
}


クライアント


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class TestClient {

public static void main(String[] args) {

try {

Socket socket = new Socket("localhost", 8888);
BufferedReader in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));

OutputStream os = socket.getOutputStream();
os.write((int)2);
os.write((int)3);
os.flush();

System.out.println(in.readLine());

// 入出力ストリームを閉じる
os.close();
in.close();
socket.close();

} catch (IOException e) {

e.printStackTrace();
}
}
}

0 コメント: