Socket(java基础)
Client Demo:
package com.demo.client;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientDemo {
public static void main(String[] args) {
try {
new ClientDemo().client();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void client() throws UnknownHostException, IOException{
Socket so=new Socket("localhost",8000);
}
}
ServiceDemo:
package com.demo.service;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServiceDemo {
public static void main(String[] args) {
try {
new ServiceDemo().service();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void service() throws IOException{
ServerSocket server=new ServerSocket(8000);
while(true){
System.out.println("正在等待客户端连接");
Socket so =server.accept();//监听客户端连接
System.out.println("客户端连接成功");
}
}
}