客户端代码
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws IOException {
//先建立端口
Socket socket = new Socket(InetAddress.getLocalHost(),20000);
//建立工作者
Woker woker = new Woker(socket);
//向服务器发送数据的线程
new Thread(new Sender(woker)).start();
//接受服务器数据的线程
new Thread(new Receiver(woker)).start();
}
}
服务端代码
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket socket1 = new ServerSocket(20000);
Socket socket = socket1.accept();
//工作者
Woker woker = new Woker(socket);
//向客户端发送数据线程
new Thread(new Sender(woker)).start();
//接受客户端数据线程
new Thread(new Receiver(woker)).start();
}
}
工作类(将数据的发送与接收面向对象)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class Woker {
Socket socket;
BufferedReader buf ;
BufferedWriter buw ;
BufferedReader in ;
public Woker(Socket socket) throws IOException {
this.socket = socket;
buf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
buw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
in = new BufferedReader(new InputStreamReader(System.in));
}
public void send() throws IOException {
while(true) {
buw.write(in.readLine());
buw.newLine();
buw.flush();
}
}
public void receive() throws IOException {
while(true) {
System.out.println(buf.readLine());
}
}
}
发送线程
import java.io.IOException;
public class Sender implements Runnable{
Woker woker ;
public Sender(Woker woker) {
this.woker = woker;
}
@Override
public void run() {
try {
woker.send();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
接收线程
import java.io.IOException;
public class Receiver implements Runnable{
Woker woker ;
public Receiver(Woker woker) {
this.woker = woker;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
woker.receive();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}