Skip to content

Instantly share code, notes, and snippets.

@seraekim
Last active April 15, 2018 07:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seraekim/28c2ce55bce98c7732be33a474b4d55e to your computer and use it in GitHub Desktop.
Save seraekim/28c2ce55bce98c7732be33a474b4d55e to your computer and use it in GitHub Desktop.
Java Socket Programming dealing with only byte arrays as in/output data using thread pool
package test_socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* up to 3 clients can access simultaneously and the others have to queue.
*
*
* @author Serae Kim
*
*/
public class Client implements Runnable {
Thread thread;
Socket s;
InputStream in;
OutputStream out;
public Client() {
if (connect()) {
try {
System.out.println("고객접속");
// 0: protocol, -55: data
out.write(new byte[]{0,-55});
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Client();
}
@Override
public void run() {
boolean isContinued = true;
while (isContinued) {
byte[] protocol = new byte[1];
try {
int isValid = in.read(protocol);
byte msg = -100;
if (isValid > 0) {
switch (protocol[0]) {
case 100:
// get client no
msg = (byte) in.read();
System.out.println("client 100|" + msg);
out.write(new byte[] { 1, 2, 3, 4, 5});
break;
case 101:
msg = (byte) in.read();
System.out.println("client 101|" + msg);
// 2 means notifying close to the server
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
out.write(new byte[] { 2 });
isContinued = false;
System.out.println("client end");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (s != null) {
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
boolean connect() {
try {
s = new Socket("localhost", 10000);
in = s.getInputStream();
out = s.getOutputStream();
thread = new Thread(this);
thread.start();
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
package test_socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* Dealing with multiple client objects from server side
* playing a role of interface for clients and server
*
* @author Serae Kim
*
*/
public class ClientCopy implements Runnable {
static int count = 0;
int clientNo = 0;
Socket s;
InputStream in;
OutputStream out;
Server server;
public ClientCopy(Socket s, Server server) {
this.s = s;
this.server = server;
this.clientNo = ++count;
try {
in = s.getInputStream();
out = s.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
boolean isContinued = true;
while (isContinued) {
byte[] protocol = new byte[1];
try {
int isValid = in.read(protocol);
byte msg = -100;
if (isValid > 0) {
switch (protocol[0]) {
// client connect
case 0:
server.addClient(this);
// should be -55
msg = (byte) in.read();
System.out.println("server 0|" + msg);
// send -55
out.write(new byte[] { 100, msg });
break;
case 1:
// 2
msg = (byte) in.read();
System.out.println("server 1|" + msg);
out.write(new byte[] { 101, msg });
break;
// get 2 and remove the client from the client pool.
case 2:
System.out.println("server 2| 종료");
// 서버로부터 종료처리.
server.removeClient(this);
isContinued = false;
break;
}
}
} catch (IOException e) {
// if socket is closed abruptly, remove it from client pool.
server.removeClient(this);
isContinued = false;
}
}
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (s != null) {
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package test_socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server implements Runnable {
// java socketserver serves 50 ports as default.
// can modify the number of ports using Executor
ExecutorService threadPool = Executors.newFixedThreadPool(3);
int port = 10000;
ServerSocket ss;
List<ClientCopy> list;
public static void main(String[] args) {
new Thread(new Server()).start();
}
public Server() {
try {
ss = new ServerSocket(port);
list = new ArrayList<ClientCopy>();
System.out.println("server start!");
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
// waiting for client connection
Socket s = ss.accept();
threadPool.execute(new ClientCopy(s, this));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void addClient(ClientCopy cc) { // to update client list
list.add(cc);
System.out.println("고객"+cc.clientNo+" 접속==========");
System.out.println("동시접속인원:" + list.size());
}
public void removeClient(ClientCopy cc) {
System.out.println("고객"+cc.clientNo+" 퇴장============");
list.remove(cc);
System.out.println("동시접속인원:" + list.size());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment