Tcp网络编程
客户端程序TcpClient.java:
import java.io.*;
import java.net.*;
public class TcpClient
{
public static void main(String[] args)
{
Socket socket = null;
DataInputStream in = null;
DataOutputStream out = null;
try
{
socket = new Socket("127.0.0.1",4331);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
char c = 'a';
while(true)
{
if(c > 'z')
c = 'a';
out.writeChar(c);
char s = in.readChar(); // in读取信息,堵塞状态
System.out.println("客户收到:" + s);
c++;
Thread.sleep(500);
}
}
catch (Exception e)
{
System.out.println("服务器已断开" + e);
}
finally
{
try
{
if(in != null) in.close();
if(out != null) out.close();
if(socket != null) socket.close();
}
catch (Exception e)
{
}
}
}
}
服务器端程序TcpServer.java:
import java.io.*;
import java.net.*;
public class TcpServer
{
public static void main(String[] args)
{
ServerSocket server = null;
Socket client = null;
try
{
server = new ServerSocket(4331);
}
catch (IOException e)
{
System.out.println(e);
}
try
{
System.out.println("等待客户端呼叫");
while(true)
{
client = server.accept(); // 堵塞状态,除非有客户端呼叫
System.out.println("新的客户端已建立连接");
new Server_thread(client).start(); // 为每个客户端启动一个专门的线程
}
}
catch (IOException e)
{
System.out.println("正在等待客户端");
}
finally
{
try
{
if(server != null) server.close();
}
catch (Exception e)
{
}
}
}
}
class Server_thread extends Thread
{
Socket socket;
DataOutputStream out = null;
DataInputStream in = null;
String s = null;
boolean quesion = false;
Server_thread(Socket t)
{
socket = t;
try
{
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
}
catch (IOException e)
{
}
}
public void run()
{
try
{
while(true)
{
char c = in.readChar(); // in读取信息,堵塞状态
System.out.println("服务器收到:" + c);
out.writeChar((char)(c-32));
Thread.sleep(500);
}
}
catch (Exception e)
{
}
}
}
注1:服务器端利用多线程处理客户端
注2:所谓“接收”客户端的套接字连接就是accept()会返回一个和客户端Socket对象相连接的Socket对象,服务器端的这个Socket对象client使用getOutputStream()方法获得的输出流将指向客户端Socket对象socket使用getInputStream()方法获得的那个输入流;同样,服务器端的这个Socket对象client使用getInputStream()方法获得的输入流将指向客户端Socket对象socket使用getOutputStream()方法获得的那个输出流。
浙公网安备 33010602011771号