TCP通信用到Socket和ServerSocket两个类。
利用线程来实现TCP互相通信。源码如下:
server端:
import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class tcpServer { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(20005); final Socket s = serverSocket.accept(); new Thread(){ @Override public void run() { while(true) { try { InputStream is = s.getInputStream(); byte [] b = new byte[1024]; int len = is.read(b); System.out.println(new String(b)); } catch (Exception e) { } } } }.start(); new Thread(){ @Override public void run() { try { while(true) { OutputStream os = s.getOutputStream(); String buf = new Scanner(System.in).next(); os.write(buf.getBytes()); } }catch (Exception e){ } } }.start(); } }
client端:
import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.util.Scanner; public class tcpClient { public static void main(String[] args) throws Exception{ final Socket socket = new Socket(InetAddress.getLocalHost().getHostAddress(),20005); new Thread(){ @Override public void run() { try { while(true) { OutputStream os = socket.getOutputStream(); String s = new Scanner(System.in).next(); os.write(s.getBytes()); } }catch (Exception e){ } } }.start(); new Thread(){ @Override public void run() { while(true) { try { InputStream is = socket.getInputStream(); byte [] b = new byte[1024]; int len = is.read(b); System.out.println(new String(b)); } catch (Exception e) { } } } }.start(); } }