当前位置 : 主页 > 编程语言 > c++ >

java网络编程-TCP客户端

来源:互联网 收集:自由互联 发布时间:2021-07-03
TCP通信是有连接状态的通信,客户端和服务器必须相连才可以实现通信 package cn.mym.tcp;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import jav
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 TCPClient {

	/**
	 *

title:main

*

function:点对点通信客户端

*@author mym *@param args */ static Socket socket; static InputStream inputStream; static OutputStream outputStream; static DataInputStream dataInputStream; static DataOutputStream dataOutputStream; public static void main(String[] args) { //启动线程 new Thread(new Client()).start(); while(true){ //这里持续的发消息 try { System.out.println("给服务器发信息:"); dataOutputStream.writeUTF(new Scanner(System.in).next()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } static class Client implements Runnable{ @Override public void run() { // TODO Auto-generated method stub try { socket = new Socket("127.0.0.1", 9999);//服务器地址和端口9999 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(); } } } }
网友评论