TCP聊天工具

//前台书写

复制代码
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;


public class MyClient {

    public static void main(String[] args) throws Exception {
        //前台
        Socket client =new Socket(InetAddress.getByName("localhost"),50000);
        OutputStream os = client.getOutputStream();
        Scanner in =new Scanner(System.in);
        String next = in.next();
        os.write(next.getBytes());
        os.close();
    }
}
复制代码

//后台书写

复制代码
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class MyServer {

    public static void main(String[] args) throws Exception {
         //ServerSocket 可以      net
           //01.在server创建一个用于   监听的 Socket
            ServerSocket socket=new ServerSocket(50000);
            System.out.println("Server开始监听了,呵呵!!!~~~~~");
            //对方的数据过来,接收到   对方的数据过来的时候 以流的形态存在
            //用于通信的Socket
            while(true){
                Socket accept=socket.accept();
                MyMethread t1=new MyMethread();
                t1.accept=accept;
                t1.start();
            }
    }
}
复制代码

//Methread

复制代码
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;


public class MyMethread extends Thread {

    public Socket accept =null;
    @Override
    public void run() {
        try {
            InputStream inputStream = accept.getInputStream();
            byte [] bytes =new byte[1024];
            int data;
            if((data=inputStream.read(bytes,0,bytes.length))!=-1){
                String temp =new String(bytes,0,data);
                System.out.println(temp+"	"+accept.getPort());
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
复制代码
原文地址:https://www.cnblogs.com/WuXuanKun/p/5786275.html