当前位置:   article > 正文

java连接tcp服务器端_java网络编程-TCP服务器端

java远程对接第三方tcp server

TCP通信是有连接状态的通信,客户端和服务器必须相连才可以实现通信

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();

}

}

}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/356673
推荐阅读
相关标签
  

闽ICP备14008679号