服务端代码:
public class MyServer {
public static void main(String[] args) {
new MyServer().initServer(10099);
}
public void initServer(int port) {
try {
ServerSocket server = new ServerSocket(port);
System.out.println("服务器已经启动....");
int count = 0;
//如果有多个客户端连接上来,服务端重新为客户端分配线程,这是一个服务端对应多个客户端的关键
while (true) {
count++;
Socket socket = server.accept();
System.out.println("已经连接" + (count) + "客户端:" + socket.getRemoteSocketAddress());
// 启动服务端接收客户端的消息的进程
new Thread(new ReceiveThread(socket)).start();
//启动段服务端向客户端发送消息的进程
new Thread(new SendThread(socket)).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 服务端发送消息的线程
*
* @author wangjue
*
*/
public class SendThread implements Runnable {
private Socket socket;
public SendThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
OutputStream ops = socket.getOutputStream();
while (true) {
Scanner sc = new Scanner(System.in);
//发送的消息以换行符结束
String s = sc.nextLine() + "\n";
ops.write(s.getBytes());
ops.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 服务端接收客户端的消息的线程
*
* @author wangjue
*
*/
public class ReceiveThread implements Runnable {
private Socket socket;
public ReceiveThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream ips = socket.getInputStream();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
while (true) {
int t = ips.read();
//读到换行符结束
while (t != '\n') {
bao.write(t);
t = ips.read();
}
byte[] b = bao.toByteArray();
String msg = new String(b);
System.out.println("客户端说" + msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端
public class MyClient {
public static void main(String[] args) {
new MyClient().initClient("127.0.0.1", 10099);
}
public void initClient(String host, int port) {
Socket socket;
try {
socket = new Socket(host, port);
//启动客户端接收服务端的进程
new Thread(new ReceiveThread(socket)).start();
//启动客户端向服务端发送消息的进程
new Thread(new SendThread(socket)).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端接收和发送消息与服务端的进程代码一样,大家有兴趣的话可以自己尝试着写一写。