TCP通信是有连接状态的通信,客户端和服务器必须相连才可以实现通信 package cn.mym.tcp;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import jav
package cn.mym.tcp; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class TCPServer { /** *title:main
*function:点对点通信服务器
*@author mym *@param args */ static ServerSocket serverSocket; static Socket socket; static InputStream inputStream; static OutputStream outputStream; static DataInputStream dataInputStream; static DataOutputStream dataOutputStream; static Scanner sinput = new Scanner(System.in); public static void main(String[] args) { //启动线程 new Thread(new Server()).start(); String toMsg; while(true){ //这里持续的发消息 try { System.out.println("给客户端发信息:"); toMsg = sinput.next(); dataOutputStream.writeUTF(toMsg); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } static class Server implements Runnable{ @Override public void run() { // TODO Auto-generated method stub try { serverSocket = new ServerSocket(9999); socket = serverSocket.accept(); //等待加入 if(socket != null){ System.out.println("客户端"+socket.getInetAddress()+"加入聊天"); while(true){ inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); dataInputStream = new DataInputStream(inputStream); dataOutputStream = new DataOutputStream(outputStream); String msg; try{ msg = dataInputStream.readUTF(); }catch(Exception e){ msg = null; } if(msg != null){ System.out.println("客户端来信:"+msg); } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }