TCP
The TCP protocol is a connection-oriented and guarantees high reliability (data without loss, data without disorder, data without error, and data without duplicate arrival).
TCP establishes a connection through three handshakes. The connection must be removed when the communication is completed. Since TCP is connected to the connection, it can only be used for end-to-end communication.
This article mainly introduces the relevant content of Java using TCP to implement simple chat. It is shared for your reference and learning. I won’t say much below. Let’s take a look at the detailed introduction together.
Sample code
Simple chat function implemented using tcp protocol (very simple)
Thought: Use 2 threads, one thread is used to receive messages, and the other thread is used to send messages.
Client Demo Code:
public class SendDemo { public static void main(String[] args) throws Exception{ Socket socket= new Socket(InetAddress.getLocalHost(),8888); SendImpl sendImpl= new SendImpl(socket); //Send thread new Thread(sendImpl).start(); //Receive thread ReciveImpl reciveImpl=new ReciveImpl(socket); new Thread(reciveImpl).start(); }}Server-side Demo Code:
public class ServerDemo { public static void main(String[] args) throws Exception { ServerSocket serverSocket =new ServerSocket(8888); Socket socket=serverSocket.accept(); SendImpl sendImpl=new SendImpl(socket); new Thread(sendImpl).start(); ReciveImpl reciveImpl=new ReciveImpl(socket); new Thread(reciveImpl).start(); }}Demo code for sending thread:
public class SendImpl implements Runnable{ private Socket socket; public SendImpl(Socket socket) { this.socket=socket; // TODO Auto-generated constructor stub } @Override public void run() { Scanner scanner=new Scanner(System.in); while(true){ try { OutputStream outputStream = socket.getOutputStream(); String string= scanner.nextLine(); outputStream.write(string.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}Demo code for receiving thread:
public class ReciveImpl implements Runnable { private Socket socket; public ReciveImpl(Socket socket) { this.socket=socket; // TODO Auto-generated constructor stub } @Override public void run() { while(true ){ try { InputStream inputStream = socket.getInputStream(); byte[] b=new byte[1024]; int len= inputStream.read(b); System.out.println("Message received: "+new String(b,0,len)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.