实现了基于TCP的Java Socket编程实例代码
程序员文章站
2024-02-20 23:04:16
实现了基于tcp的java socket编程,功能很简单:客户端向服务器端输出一名话"connect",服务器端接收输出到控制台并向客户端输出一名话"hello",客户端接...
实现了基于tcp的java socket编程,功能很简单:客户端向服务器端输出一名话"connect",服务器端接收输出到控制台并向客户端输出一名话"hello",客户端接收并输出。
1.服务器端
复制代码 代码如下:
package javase.net.socket;
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;
public class tcpserver {
public static void main(string[] args) {
try {
serversocket serversocket = new serversocket(8888);
socket socket = serversocket.accept();
// 读取客户端数据
inputstream info = socket.getinputstream();
datainputstream dis = new datainputstream(info);
system.out.println(dis.readutf());
// 向客户端输出数据
outputstream os = socket.getoutputstream();
dataoutputstream dos = new dataoutputstream(os);
dos.writeutf("hello!");
dos.flush();
} catch (ioexception e) {
e.printstacktrace();
}
}
}
2.客户端:
复制代码 代码如下:
package javase.net.socket;
import java.io.datainputstream;
import java.io.dataoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.net.socket;
import java.net.unknownhostexception;
public class tcpclient {
public static void main(string[] args) {
try {
socket socket = new socket("192.168.1.123", 8888);
// 向服务器端发送数据
outputstream os = socket.getoutputstream();
dataoutputstream bos = new dataoutputstream(os);
bos.writeutf("connect");
bos.flush();
// 接收服务器端数据
inputstream is = socket.getinputstream();
datainputstream dis = new datainputstream(is);
system.out.println(dis.readutf());
} catch (unknownhostexception e) {
e.printstacktrace();
} catch (ioexception e) {
e.printstacktrace();
}
}
}
下一篇: java获取当前日期使用实例