欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java Tcp通信客户端与服务器端实例

程序员文章站 2022-04-18 09:45:35
本文实例讲述了java tcp通信客户端与服务器端。分享给大家供大家参考,具体如下: 由服务器端发送数据 服务器端: import java.io.*; import...

本文实例讲述了java tcp通信客户端与服务器端。分享给大家供大家参考,具体如下:

由服务器端发送数据

服务器端:

import java.io.*;
import java.net.*;
public class testsocket {
 public static void main(string[] args) {
 try {
  serversocket ss = new serversocket(8888);
  while(true) {
  socket s = ss.accept();
  outputstream os = s.getoutputstream();
  dataoutputstream dos = new dataoutputstream(os);
  dos.writeutf("hello" + s.getinetaddress() + "port" + s.getport() + "beybye");
  dos.close();
//  os.flush();
  os.close();
//  s.close();
  }
 } catch (ioexception e) {
  e.printstacktrace();
  system.out.println("there is a wrong");
 }
 }
}

用户端:

import java.io.*;
import java.net.*;
public class testclient {
 public static void main(string[] args){
 try {
  socket s = new socket("127.0.0.1",8888);
  datainputstream dis = new datainputstream(s.getinputstream());
  system.out.println(dis.readutf()); 
  s.close();
  dis.close();
 } catch (exception e) {
  e.printstacktrace();
 }
 }
}

无论是客户端还是服务器端都可以收发数据。

交互型

用户端

import java.io.*;
import java.net.*;
public class testclient2 {
 public static void main(string[] args){
 try {
  socket s = new socket("127.0.0.1",8886);
  dataoutputstream dos = new dataoutputstream(s.getoutputstream());
  datainputstream dis = new datainputstream(s.getinputstream());
  system.out.println(dis.readutf()); 
  dos.writeutf("hey");
  string str = null;
  if((str = dis.readutf()) != null) {
  system.out.println(str);
  }
  s.close();
  dis.close();
  dos.close();
 } catch (exception e) {
  e.printstacktrace();
 }
 }
}

服务器端:

public class testserver2 {
 public static void main(string[] args) {
 inputstream in = null;
 outputstream out = null;
 try {
  serversocket ss = new serversocket(8886);
  while(true) {
  socket s = ss.accept();
  in = s.getinputstream();
  out = s.getoutputstream();
  dataoutputstream dos = new dataoutputstream(s.getoutputstream());
  datainputstream dis = new datainputstream(s.getinputstream());
  string str = null;
  if((str = dis.readutf() )!= null) {
   system.out.println(str);
   system.out.println("form " + s.getinetaddress());
   system.out.println("port " + s.getport());
//   dos.writeutf("hello" + s.getinetaddress() + "port" + s.getport() + "beybye");
  }
  dos.writeutf("hi hello");
  dis.close();
  dos.close();
  s.close();
  }
 } catch (ioexception e) {
  e.printstacktrace();
  system.out.println("there is a wrong");
 }
 }
}