首页 > 代码库 > the socket and serversocket in java
the socket and serversocket in java
the client port:
package com.socket;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class MyClient {
public static void main(String args[]) throws UnknownHostException, IOException{
Socket socket=new Socket("localhost", 10000);
OutputStream os=socket.getOutputStream();
PrintStream ps=new PrintStream(os);
ps.print("Hello, server. This is client");
ps.close();
os.close();
socket.close();
}
}
the sever port:
package com.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String args[]) throws IOException{
ServerSocket serverSocket=new ServerSocket(10000);
Socket socket=serverSocket.accept();
InputStream is=socket.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
String r_l=null;
while((r_l=br.readLine())!=null){
System.out.println(r_l);
System.out.println("hello, client. you connection is working!!!");
}
br.close();
isr.close();
serverSocket.close();
socket.close();
}
}
start server, then start client:
the console in server port is like this:
the socket and serversocket in java