Java Socket编程实例(一)- TCP基本使用
程序员文章站
2024-03-12 19:19:02
一.服务端代码:
import java.net.*; // for socket, serversocket, and inetaddress
import...
一.服务端代码:
import java.net.*; // for socket, serversocket, and inetaddress import java.io.*; // for ioexception and input/outputstream public class tcpechoserver { private static final int bufsize = 32; // size of receive buffer public static void main(string[] args) throws ioexception { int servport = 5500; // create a server socket to accept client connection requests serversocket servsock = new serversocket(servport); int recvmsgsize; // size of received message byte[] receivebuf = new byte[bufsize]; // receive buffer while (true) { // run forever, accepting and servicing connections socket clntsock = servsock.accept(); // get client connection socketaddress clientaddress = clntsock.getremotesocketaddress(); system.out.println("handling client at " + clientaddress); inputstream in = clntsock.getinputstream(); outputstream out = clntsock.getoutputstream(); // receive until client closes connection, indicated by -1 return while ((recvmsgsize = in.read(receivebuf)) != -1) { out.write(receivebuf, 0, recvmsgsize); } clntsock.close(); // close the socket. we are done with this client! } /* not reached */ } }
二.客户端代码:
import java.net.*; import java.io.*; public class tcpechoclient { public static void main(string[] args) throws ioexception { string server = "127.0.0.1"; // server name or ip address int servport = 5500; //// server port byte[] data = "hi, world".getbytes(); // create socket that is connected to server on specified port socket socket = new socket(server, servport); system.out.println("connected to server...sending echo string"); inputstream in = socket.getinputstream(); outputstream out = socket.getoutputstream(); out.write(data); // send the encoded string to the server // receive the same string back from the server int totalbytesrcvd = 0; // total bytes received so far int bytesrcvd; // bytes received in last read while (totalbytesrcvd < data.length) { if ((bytesrcvd = in.read(data, totalbytesrcvd, data.length - totalbytesrcvd)) == -1) throw new socketexception("connection closed prematurely"); totalbytesrcvd += bytesrcvd; } // data array is full system.out.println("received: " + new string(data)); socket.close(); // close the socket and its streams } }
上述代码的tcp服务端是单线程,一次只能服务一个客户端。
查看更多java的语法,大家可以关注:《thinking in java 中文手册》、《jdk 1.7 参考手册官方英文版》、《jdk 1.6 api java 中文参考手册》、《jdk 1.5 api java 中文参考手册》,也希望大家多多支持。