package myk; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class TcpServer { /** * Socket编程 服务器端 */ public static void main(String[] args) { ServerSocket svrsoc = null; Socket soc = null; InputStream is = null; OutputStream os = null; // DataInputStream 为InputStream的子类 DataInputStream in = null; // PrintStream为OutputStream的子类 PrintStream out = null; // 构造serverSocket对象 try { svrsoc = new ServerSocket(9999); /** * 让服务器端一直等待,直到客户端连接到该端口 服务器等待一个连接,返回新套接口soc,新套接口soc实现了 与客户端建立的套接口连接 */ soc = svrsoc.accept(); // 接收客户端的输入 is = soc.getInputStream(); in = new DataInputStream(is); // 向客户端输出 os = soc.getOutputStream(); out = new PrintStream(os); // 获取客户端的ip地址 InetAddress clientIP = soc.getInetAddress(); // 获取客户端的端口 int port = soc.getPort(); System.out.println(clientIP+":"+port); //向客户端发送信息 out.println("welcome!。。。。。 "); /**用于从输入流中读取客户端输入的一行信息,直到读入quit才停止*/ String str = in.readLine(); while(!str.equals("quit")){ System.out.println(str); str = in.readLine(); } System.out.println("Client want to leave!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { is.close(); in.close(); os.close(); out.close(); soc.close(); System.exit(0); } catch (IOException e) { e.printStackTrace(); } } } }
package myk; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; public class TcpClient { /** * Socket 客户端 */ public static void main(String[] args) { Socket soc = null; InputStream is = null; OutputStream os = null; // DataInputStream 为InputStream的子类 DataInputStream in = null; // PrintStream为OutputStream的子类 PrintStream out = null; String strin = null; try { //客户机 soc = new Socket("localhost",9999); System.out.println("Connect to server...."); is = soc.getInputStream(); os = soc.getOutputStream(); in = new DataInputStream(is); out = new PrintStream(os); //数据读入流(从服务器读取数据) strin = in.readLine(); System.out.println("server said:"+strin); byte bmsg[] = new byte[20]; System.in.read(bmsg); String msg = new String(bmsg,0); //当从键盘读入的不是quit,将键入的数据写入输出流中,然后从键盘继续读入 msg = msg.trim(); while(!msg.equals("quit")){ out.println(msg); System.in.read(bmsg); msg = new String(bmsg,0); msg = msg.trim(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { is.close(); os.close(); in.close(); out.close(); System.exit(0); } catch (IOException e) { e.printStackTrace(); } } } }