编写Server和Client间的通话,首先Server要启动ServerSocket,Client端要启动Socket,然后Server端要不断的accept();然后他们间的通话用流的形式传递,用DataInputStream or DataOutputStream,中的readUTF()和writeUTF()方法.最后还要关闭流,关闭Socket.还不要忘了还要处理异常。代码如下:
import java.net.*;import java.io.*;public class TcpClient { public static void main(String[] args) { try { Socket ss = new Socket("127.0.0.1", 6666); DataInputStream di = new DataInputStream(ss.getInputStream()); DataOutputStream dz = new DataOutputStream(ss.getOutputStream()); dz.writeUTF("我爱你"); dz.flush(); System.out.println(di.readUTF()); di.close(); dz.close(); ss.close(); } catch (IOException e) { System.exit(0); } }}
import java.net.*;import java.io.*;public class TcpServer { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(6666); while (true) { Socket s = ss.accept(); System.out.println("已经连上了"); DataOutputStream ds = new DataOutputStream(s.getOutputStream()); DataInputStream di = new DataInputStream(s.getInputStream()); String z="";z=di.readUTF(); if (z!= null) { System.out.println(z); System.out.println("我收到了"); } ds.writeUTF("你好吗"); ds.flush(); ds.close(); di.close(); s.close(); } } catch (IOException e) { System.exit(-1); } }}