ServerSocket类
ServerSocket myListener = new ServerSocket(600);
提供监听服务的端口是600,不同服务之间通过端口来区别。为了随时监听可能的Client端的请求,执行如
下语句:
Socket linkSockt = myListener.accept();
这个方法执行将使得Server端处于等待状态,直到接收一个来自Client端的请求,并返回一个与Client通信
的Socket对象。Server端与Client端连接后,就实现了相互读写数据,结束通信执行:
myListener.close();
Socket类
Client需从Server获取服务时,应创建一个Socket对象:
Socket mySocket = new Socket(host,port);
连通后,利用Socket类方法getOutputStream()获取(write)输出流,和getInputStream()获取(read)输
入流。结束通信同样是
mySocket.close();
ServerSocket一般仅用于设置端口号和监听,真正进行通信的是Server端的Socket与Client端的Socket,在ServerSocket进行accept后,就将主动权转让给Server端的Socket。
Server端
package com.serversocket.test;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
private ServerSocket ss;
public static final int port = 8962;
public MyServer(){
try{
ss = new ServerSocket(port);
}
catch(IOException e){
e.printStackTrace();
}
}
public void setConnection() throws IOException{
Socket s;
OutputStream os;
try {
s = ss.accept();
os = s.getOutputStream();
os.write("hello".getBytes());
os.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException{
MyServer ms = new MyServer();
ms.setConnection();
}
}
Client端
package com.serversocket.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class MyClient {
public static final String IP = "127.0.0.1";
public static int port = 8962;
private Socket s;
public MyClient(){
try {
s = new Socket(IP,port);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setConnection() throws IOException{
InputStream is;
try {
is = s.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException{
MyClient mc = new MyClient();
mc.setConnection();
}
}
来自网络资料