socket用于描述IP地址和端口,是一个通信链的句柄。在Internet上的主机一般运行了多个服务软件,同时提供几种服务。每种服务都打开一个Socket,并绑定到一个端口上,不同的端口对应于不同的服务。
java中当连接到一个套接字时,当前线程对被阻塞,直到建立连接或者超时为止。同样,当通过套接字读写数据时,当前线程也会被阻塞,直到操作成功或者超时。
本例:Client与Server之间的通信。
服务器端:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class EchoServer {
private Scanner in; //服务器从客户端读入的流
private PrintWriter out; //服务器从客户端输出的流
private Scanner input; //从键盘中读取的数据
private boolean stop=false;
public EchoServer(ServerSocket server) throws IOException{
Socket s=server.accept();
System.out.println("有一位客户端连接到服务器");
in=new Scanner(s.getInputStream());
out=new PrintWriter(s.getOutputStream());
input=new Scanner(System.in);
out.println("连接服务器成功,输入BYE结束");
out.flush();
startRead(); //开启不断从客户端读取的进程
startWrite(); //开启不断向客户端写的进程
}
private void startRead() {
new Thread(new Runnable(){
@Override
public void run() {
while(!stop&&in.hasNextLine()){
String line=in.nextLine();
System.out.println("Client:"+line);
if(line.equals("BYE"))
stop=true;
}
}
}).start();
}
private void startWrite() {
new Thread(new Runnable(){
@Override
public void run() {
while(!stop&&input.hasNextLine()){
String line=input.nextLine();
out.println(line);
out.flush();
if(line.equals("BYE"))
stop=true;
}
}
}).start();
}
}
import java.io.IOException;
import java.net.ServerSocket;
public class ServerSocketTest {
public static void main(String[] args) throws IOException {
ServerSocket server=new ServerSocket(8808);
new EchoServer(server);
}
}
客户端程序:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
private Socket s;
private Scanner in; //客户端从服务器读入的流
private PrintWriter out; //客户端向服务器输出的流
private Scanner input; //从键盘中读取的数据
private boolean stop=false;
public Client(int port) throws UnknownHostException, IOException{
s=new Socket("127.0.0.1",port);
in=new Scanner(s.getInputStream());
out=new PrintWriter(s.getOutputStream());
input=new Scanner(System.in);
startRead(); //开启不断从服务器读取的进程
startWrite(); //开启不断向服务器写的进程
}
private void startRead() {
new Thread(new Runnable(){
@Override
public void run() {
while(!stop&&in.hasNextLine()){
String line=in.nextLine();
System.out.println("Server:"+line);
if(line.equals("BYE"))
stop=true;
}
}
}).start();
}
private void startWrite() {
new Thread(new Runnable(){
@Override
public void run() {
while(!stop&&input.hasNextLine()){
String line=input.nextLine();
out.println(line);
out.flush();
if(line.equals("BYE"))
stop=true;
}
}
}).start();
}
}
import java.io.IOException;
import java.net.UnknownHostException;
public class ClientTest {
public static void main(String[] args) throws UnknownHostException, IOException{
new Client(8808);
}
}
运行结果(服务器端先运行):
服务器端:
有一位客户端连接到服务器
Client:你好
你好 我是服务器
你是谁
Client:我是客户端
Client:BYE
BYE
客户端:
Server:连接服务器成功,输入BYE结束
你好
Server:你好 我是服务器
Server:你是谁
我是客户端
BYE
Server:BYE