연습: 다중 스레드 TCP 서버 및 클라이언트 만들기
3948 단어 자바스 연습 문제.
class Client implements Runnable {
private Socket s;
private Scanner sc;
{
sc = new Scanner(System.in);
}
public void run() {
s = new Socket();
try {
s.connect(new InetSocketAddress("localhost", 8090));
String year = sc.nextLine();
s.getOutputStream().write(year.getBytes());
s.shutdownOutput();
byte[] bs = new byte[1024];
int len = s.getInputStream().read(bs);
s.shutdownInput();
System.out.println(new String(bs, 0, len));
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server implements Runnable {
private ServerSocket ss;
private Map map = new HashMap<>();
{
try {
BufferedReader reader = new BufferedReader(new FileReader("worldcup.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
String[] strs = line.split("/");
map.put(strs[0], strs[1]);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
ss = new ServerSocket(8090);
Socket s = ss.accept();
byte[] bs = new byte[1024];
int len = s.getInputStream().read(bs);
s.shutdownInput();
String year = new String(bs, 0, len);
String dest = map.containsKey(year) ? map.get(year) : " ";
s.getOutputStream().write(dest.getBytes());
s.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}
}
}