//TCP/IP服务器 import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class TestSocketServer { ServerSocket serverSocket; int portNumber=9001; Socket socket; String str; public TestSocketServer(){ str="Hello,I am Server!"; try { //使用端口号创建一个serverSocket对象 serverSocket=new ServerSocket(portNumber); //等待一个客户连接端口xx的服务器 socket=serverSocket.accept(); //创建流发送数据 ObjectOutputStream oos =new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(str); //关闭流和套接字 oos.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[]args){ TestSocketServer tss=new TestSocketServer(); } }
//TCP/IP客户 import java.io.ObjectInputStream; import java.net.InetAddress; import java.net.Socket; public class TestSocketClient { Socket socket ; int portNumber=9001; String string=""; public TestSocketClient(){ try { //创建Socket类对象,向它传递服务器的IP地址和服务器监听端口 socket =new Socket(InetAddress.getLocalHost(),portNumber); //创建输入流,访问数据 ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); //读取对象 string=(String)ois.readObject(); System.out.println(string); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[]args){ TestSocketClient tcp=new TestSocketClient(); } }