服务器端(Server)非多线程
- package com.zeph.serverclient;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class MyServer {
- public static void main(String[] args) throws IOException {
- ServerSocket server = new ServerSocket(5678);
- Socket client = server.accept();
- BufferedReader in = new BufferedReader(new InputStreamReader(
- client.getInputStream()));
- PrintWriter out = new PrintWriter(client.getOutputStream());
- while (true) {
- String str = in.readLine();
- System.out.println(str);
- out.println("has receive....");
- out.flush();
- if (str.equals("end"))
- break;
- }
- client.close();
- }
- }
客户端(Client)
- package com.zeph.serverclient;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.InetAddress;
- import java.net.Socket;
- public class MyClient {
- static Socket server;
- public static void main(String[] args) throws Exception {
- server = new Socket(InetAddress.getLocalHost(), 5678);
- BufferedReader in = new BufferedReader(new InputStreamReader(
- server.getInputStream()));
- PrintWriter out = new PrintWriter(server.getOutputStream());
- BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
- while (true) {
- String str = wt.readLine();
- out.println(str);
- out.flush();
- if (str.equals("end")) {
- break;
- }
- System.out.println(in.readLine());
- }
- server.close();
- }
- }
服务器端(Server)多线程
- package com.zeph.multiclient;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class MultiClient extends Thread {
- private Socket client;
- public MultiClient(Socket c) {
- this.client = c;
- }
- public void run() {
- try {
- BufferedReader in = new BufferedReader(new InputStreamReader(
- client.getInputStream()));
- PrintWriter out = new PrintWriter(client.getOutputStream());
- // Mutil User but can't parallel
- while (true) {
- String str = in.readLine();
- System.out.println(str);
- out.println("has receive....");
- out.flush();
- if (str.equals("end"))
- break;
- }
- client.close();
- } catch (IOException ex) {
- } finally {
- }
- }
- public static void main(String[] args) throws IOException {
- ServerSocket server = new ServerSocket(5678);
- while (true) {
- // transfer location change Single User or Multi User
- MultiClient mc = new MultiClient(server.accept());
- mc.start();
- }
- }
- }
测试这个代码的时候可以直接用DOS控制台上面运行,这样看的效果更清楚!
服务器基本步骤:
1.指定端口实例化一个SeverSocket
2.调用ServerSocket的accept()方法,以在等待连接期间造成阻塞
3.获取位于该底层的Socket的流以进行读写操作
4.将数据封装成流
5.对Socket进行读写
6.关闭打开的流
客户端基本步骤:
1.通过IP地址和端口实例化Socket,请求连接服务器
2.获得Socket上的流以进行读写
3.把流封装进BufferedReader/PrintWriter的实例
4.对Socket进行读写
5.关闭打开的流