Java中接受其他通信实体连接请求的类是ServerSocket。该对象用于监听来自客户端的Socket连接,如没连接,一直处于等待状态。
客户端使用用Socket来的构造器来连接指定服务器。
以下是两端的code示例:
public class Client
{
public static void main(String[] args) throws IOException
{
Socket s = new Socket(“127.0.0.1”,30000);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputSteam()));
System.out.println("come from server:" + br.readLine());
br.close();
socket.close();
}
}
public class Server
{
public static void main(String[] args) throws IOException
{
Socket ss = new ServerSocket(30000);
while(true)
{
Socket s = ss.accept();
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println("welcome to receive msg from server")
}
ps.close();
s.close();
}
}
多线程:下面实现一个客户端(一个Socket对应一个线程,一个客户端)将读取的信息广播到其他客户端。
public class MyServer
{
//save all ArrayList of Socket
public static ArrayList<Socket> socketList = new ArrayList<Socket>();
public static void mian(String[] args) throws IOException
{
ServerSocket ss =new ServerSocket(30000);
while(true)
{
//waiting for others'link
Socket s = ss.accept();
sockeList.add(s);
//when client link ,then star a ServerThread for it
new Thread(new ServerThread(s)).start();
}
}
}
public class ServerThread implements Runnable
{
//define current thread processed Socket
Socket s = null;
//IO with this thread
BufferedReader br =null;
public ServerThread(Socket s)throws IOException
{
this.s=s;
//int Socket IO
br= new BufferedReader(new InpuStreamReader(s.getInputStream()));
}
public void run()
{
try
{
String content = null;
while((content = readFromClient())!=null)
{
for(Socket s:MyServer.socketList)
{
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println(content);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
private String readFromClient()
{
try
{
return br.readLine();
}
catch (IOException e)
{
MyServer.socketList.remove(s);
}
return null;
}