「Java」 java.net.Socketでクライアント側、サーバー側のscoketを操作する
1.Client側
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SockClientDemo {
public static void main(String args[]) {
try {
// 4700ポートにリクエスト
Socket socket = new Socket(“127.0.0.1", 4700);
// PrintWriterオブジェクト
PrintWriter os = new PrintWriter(socket.getOutputStream());
// BufferedReaderオブジェクト
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
os.println(“it is a test demo");
os.flush();
os.close();
is.close();
socket.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}
2.Server側
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SockServerDemo {
public static void main(String args[]) {
try {
ServerSocket server = null;
//4700ポートをListen
server = new ServerSocket(4700);
Socket socket = null;
//accept()
socket = server.accept();
//BufferedReaderオブジェクト
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//PrintWriterオブジェクト
PrintWriter os = new PrintWriter(socket.getOutputStream());
System.out.println(“server:" + is.readLine());
os.close();
is.close();
socket.close();
server.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}