Java实现TCP通讯

来源:互联网 发布:淘宝联盟注册 编辑:程序博客网 时间:2024/05/22 01:32

1.服务器代码

import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class ServiceSocket extends Thread{public Socket sock;public ServiceSocket(Socket sock){this.sock=sock;}public void run(){try{OutputStream os=sock.getOutputStream();InputStream is=sock.getInputStream();os.write("Hello Welcome you".getBytes());byte []buf=new byte[100];int len=is.read(buf);System.out.println(new String(buf,0,len));os.close();is.close();sock.close();}catch(Exception e){}}public static void main(String[] args) {// TODO Auto-generated method stubtry {ServerSocket ss=new ServerSocket(6000);while(true){Socket s=ss.accept();new ServiceSocket(s).start();}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

2.客户端代码

import java.io.InputStream;import java.io.OutputStream;import java.net.InetAddress;import java.net.Socket;public class ClientSocket {public static void main(String []args){try {Socket s=new Socket(InetAddress.getByName(null),6000);//"localhost" "127.0.0.1s"OutputStream os=s.getOutputStream();InputStream is=s.getInputStream();byte []buf=new byte[100];int len=is.read(buf);System.out.println(new String(buf,0,len));os.write("Hello,this is zhangsan".getBytes());Thread.sleep(100);os.close();is.close();s.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}