通过TCP进行通信
Posted dulute
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过TCP进行通信相关的知识,希望对你有一定的参考价值。
public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(8888); System.out.println("服务器即将启动,等待客户端的连接"); Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String info = null; while ((info=br.readLine())!=null) { System.out.println("我是服务器,客户端说" + info); } br.close(); isr.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public class Client { public static void main(String[] args) { try { Socket socket = new Socket("localhost",8888); OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("用户名:admin;密码:123"); pw.flush(); socket.shutdownOutput(); pw.close(); os.close(); socket.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
以上是关于通过TCP进行通信的主要内容,如果未能解决你的问题,请参考以下文章